forked from hidevopsio/hiboot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reflect.go
448 lines (371 loc) · 10.9 KB
/
reflect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// Copyright 2018 John Deng (hi.devops.io@gmail.com).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package reflector provides utilities for reflection
package reflector
import (
"errors"
"hidevops.io/hiboot/pkg/utils/io"
"hidevops.io/hiboot/pkg/utils/str"
"reflect"
"runtime"
"strings"
)
var (
// ErrInvalidInput means that the input is invalid
ErrInvalidInput = errors.New("input is invalid")
// ErrInvalidMethod means that the method is invalid
ErrInvalidMethod = errors.New("method is invalid")
// ErrInvalidFunc means that the func is invalid
ErrInvalidFunc = errors.New("func is invalid")
// ErrFieldCanNotBeSet means that the field can not be set
ErrFieldCanNotBeSet = errors.New("field can not be set")
)
// NewReflectType create instance by tyep
func NewReflectType(st interface{}) interface{} {
ct := reflect.TypeOf(st)
co := reflect.New(ct)
cp := co.Elem().Addr().Interface()
return cp
}
// Validate validate value
func Validate(toValue interface{}) (*reflect.Value, error) {
to := Indirect(reflect.ValueOf(toValue))
// Return is from value is invalid
if !to.IsValid() {
return nil, errors.New("value is not valid")
}
if !to.CanAddr() {
return nil, errors.New("value is unaddressable")
}
return &to, nil
}
// DeepFields iterate struct field
func DeepFields(reflectType reflect.Type) []reflect.StructField {
var fields []reflect.StructField
if reflectType = IndirectType(reflectType); reflectType.Kind() == reflect.Struct {
for i := 0; i < reflectType.NumField(); i++ {
v := reflectType.Field(i)
if v.Anonymous {
fields = append(fields, DeepFields(v.Type)...)
} else {
fields = append(fields, v)
}
}
}
return fields
}
// Indirect get indirect value
func Indirect(reflectValue reflect.Value) reflect.Value {
for reflectValue.Kind() == reflect.Ptr {
reflectValue = reflectValue.Elem()
}
return reflectValue
}
// IndirectType get indirect type
func IndirectType(reflectType reflect.Type) reflect.Type {
for reflectType.Kind() == reflect.Ptr || reflectType.Kind() == reflect.Slice {
reflectType = reflectType.Elem()
}
return reflectType
}
// GetFieldValue get field value
func GetFieldValue(f interface{}, name string) reflect.Value {
r := reflect.ValueOf(f)
fv := reflect.Indirect(r).FieldByName(name)
return fv
}
// SetFieldValue set field value
func SetFieldValue(object interface{}, name string, value interface{}) error {
obj := Indirect(reflect.ValueOf(object))
if !obj.IsValid() {
return ErrInvalidInput
}
if obj.Kind() != reflect.Struct {
return ErrInvalidInput
}
fieldObj := obj.FieldByName(name)
if !fieldObj.CanSet() {
return ErrFieldCanNotBeSet
}
fov := reflect.ValueOf(value)
fieldObj.Set(fov)
//log.Debugf("Set %v.(%v) into %v.%v", value, fov.Type(), obj.Type(), name)
return nil
}
// GetKind get kind
func GetKind(kind reflect.Kind) reflect.Kind {
// Check each condition until a case is true.
switch {
case kind >= reflect.Int && kind <= reflect.Int64:
return reflect.Int
case kind >= reflect.Uint && kind <= reflect.Uint64:
return reflect.Uint
case kind >= reflect.Float32 && kind <= reflect.Float64:
return reflect.Float32
default:
return kind
}
}
// GetKindByValue get kind by value
func GetKindByValue(val reflect.Value) reflect.Kind {
return GetKind(val.Kind())
}
// GetKindByType get kind by type
func GetKindByType(typ reflect.Type) reflect.Kind {
return GetKind(typ.Kind())
}
// ValidateReflectType validate reflect type and iterate all fields
func ValidateReflectType(obj interface{}, callback func(value *reflect.Value, reflectType reflect.Type, fieldSize int, isSlice bool) error) error {
v, err := Validate(obj)
if err != nil {
return err
}
t := IndirectType(v.Type())
isSlice := false
fieldSize := 1
if v.Kind() == reflect.Slice {
isSlice = true
fieldSize = v.Len()
}
if callback != nil {
return callback(v, t, fieldSize, isSlice)
}
return err
}
// GetType get object data type
func GetType(data interface{}) (typ reflect.Type, err error) {
dv := Indirect(reflect.ValueOf(data))
// Return is from value is invalid
if !dv.IsValid() {
err = ErrInvalidInput
return
}
typ = dv.Type()
//log.Debugf("%v %v %v %v %v", dv, typ, typ.String(), typ.Name(), typ.PkgPath())
return
}
// GetFuncName get func name
func GetFuncName(fn interface{}) (name string) {
val := reflect.ValueOf(fn)
kind := val.Kind()
if kind == reflect.Func {
name = runtime.FuncForPC(val.Pointer()).Name()
n := strings.LastIndexByte(name, byte('.'))
if n > 0 {
name = name[n+1:]
n = strings.LastIndexByte(name, byte('-'))
if n > 0 {
name = name[:n]
}
n = strings.LastIndexByte(name, byte(')'))
if n > 0 {
name = name[:n]
}
}
}
return
}
// GetName get object name
func GetName(data interface{}) (name string) {
typ, err := GetType(data)
if err == nil {
name = typ.Name()
}
return
}
// GetLowerCamelName get lower case object name
func GetLowerCamelName(object interface{}) (name string) {
name = GetName(object)
name = str.ToLowerCamel(name)
return name
}
// HasField check if has specific field
func HasField(object interface{}, name string) bool {
r := reflect.ValueOf(object)
fv := reflect.Indirect(r).FieldByName(name)
return fv.IsValid()
}
// CallMethodByName call method
func CallMethodByName(object interface{}, name string, args ...interface{}) (interface{}, error) {
objVal := reflect.ValueOf(object)
method, ok := objVal.Type().MethodByName(name)
if ok {
numIn := method.Type.NumIn()
inputs := make([]reflect.Value, numIn)
inputs[0] = objVal
for i, arg := range args {
inputs[i+1] = reflect.ValueOf(arg)
}
results := method.Func.Call(inputs)
if len(results) != 0 {
return results[0].Interface(), nil
}
return nil, nil
}
return nil, ErrInvalidMethod
}
// CallFunc call function
func CallFunc(object interface{}, args ...interface{}) (interface{}, error) {
fn := reflect.ValueOf(object)
if fn.Kind() == reflect.Func {
numIn := fn.Type().NumIn()
inputs := make([]reflect.Value, numIn)
for i, arg := range args {
inputs[i] = reflect.ValueOf(arg)
}
results := fn.Call(inputs)
if len(results) != 0 {
return results[0].Interface(), nil
}
return nil, nil
}
return nil, ErrInvalidFunc
}
// HasEmbeddedField check if has embedded fieled
func HasEmbeddedField(object interface{}, name string) bool {
//log.Debugf("HasEmbeddedField: %v", name)
typ := IndirectType(reflect.TypeOf(object))
if typ.Kind() != reflect.Struct {
return false
}
field, ok := typ.FieldByName(name)
return field.Anonymous && ok
}
// HasEmbeddedFieldType check if has embedded fieled
func HasEmbeddedFieldType(object interface{}, expected interface{}) (found bool) {
typ, _ := GetObjectType(object)
expectedTyp, _ := GetObjectType(expected)
field := GetEmbeddedFieldByType(typ, expectedTyp.Name(), expectedTyp.Kind())
return field.Anonymous
}
// GetEmbeddedFieldByType get embedded interface field by type
func GetEmbeddedFieldByType(typ reflect.Type, name string, kind ...reflect.Kind) (field reflect.StructField) {
expectedKind := reflect.Interface
if len(kind) > 0 {
expectedKind = kind[0]
}
if typ.Kind() == reflect.Struct {
for i := 0; i < typ.NumField(); i++ {
v := typ.Field(i)
if v.Anonymous {
if v.Type.Kind() == expectedKind && (name == "" || v.Name == name) {
return v
}
return GetEmbeddedFieldByType(v.Type, name)
}
}
}
return
}
// GetEmbeddedField get embedded interface field
func GetEmbeddedField(object interface{}, name string, dataTypes ...reflect.Kind) (field reflect.StructField) {
if object == nil {
return
}
typ, ok := GetObjectType(object)
if ok {
field = GetEmbeddedFieldByType(typ, name, dataTypes...)
}
return
}
// FindEmbeddedFieldTag find embedded field tag
func FindEmbeddedFieldTag(object interface{}, fieldName, tagName string) (t string, ok bool) {
f := GetEmbeddedField(object, fieldName)
t, ok = f.Tag.Lookup(tagName)
return
}
// ParseObjectName e.g. ExampleObject => example
func ParseObjectName(obj interface{}, eliminator string) string {
name := GetName(obj)
name = strings.Replace(name, eliminator, "", -1)
name = str.LowerFirst(name)
return name
}
// ParseObjectPkgName e.g. ExampleObject => example
func ParseObjectPkgName(obj interface{}) string {
typ := IndirectType(reflect.TypeOf(obj))
name := io.DirName(typ.PkgPath())
return name
}
// GetPkgPath get the package patch
func GetPkgPath(object interface{}) string {
objType := IndirectType(reflect.TypeOf(object))
return objType.PkgPath()
}
// GetObjectType get the function output data type
func GetObjectType(object interface{}) (typ reflect.Type, ok bool) {
obj := reflect.ValueOf(object)
t := obj.Type()
typName := t.Name()
typKind := t.Kind()
//log.Debugf("type: %v type name: %v, kind: %v", t, typName, typKind)
if typKind == reflect.Func {
numOut := obj.Type().NumOut()
if numOut > 0 {
typ = IndirectType(obj.Type().Out(0))
ok = true
}
} else if typKind == reflect.Struct && typName == "Method" {
method := object.(reflect.Method)
methodTyp := method.Func.Type()
numOut := methodTyp.NumOut()
if numOut > 0 {
typ = IndirectType(methodTyp.Out(0))
ok = true
}
} else {
// TODO: check if it effects others
typ = IndirectType(t)
ok = true
}
return
}
// GetFullName get the object name with package name, e.g. pkg.Object
func GetFullName(object interface{}) (name string) {
pn, n := GetPkgAndName(object)
name = pn + "." + n
return
}
// GetLowerCamelFullName get the object name with package name, e.g. pkg.objectName
func GetLowerCamelFullName(object interface{}) (name string) {
pn, n := GetPkgAndName(object)
name = pn + "." + str.ToLowerCamel(n)
return
}
// GetPkgAndName get the package name and the object name with, e.g. pkg, Object
func GetPkgAndName(object interface{}) (pkgName, name string) {
typ, ok := GetObjectType(object)
if ok {
pkgName = io.DirName(typ.PkgPath())
name = typ.Name()
}
return
}
// GetLowerCamelFullNameByType get the object name with package name by type, e.g. pkg.Object
func GetLowerCamelFullNameByType(objType reflect.Type) (name string) {
indTyp := IndirectType(objType)
depPkgName := io.DirName(indTyp.PkgPath())
name = depPkgName + "." + str.ToLowerCamel(indTyp.Name())
return
}
// IsValidObjectType check if is valid object type
func IsValidObjectType(inst interface{}) bool {
val := reflect.ValueOf(inst)
//log.Println(val.Kind())
//log.Println(reflect.Indirect(val).Kind())
if val.Kind() == reflect.Ptr && reflect.Indirect(val).Kind() == reflect.Struct {
return true
}
return false
}