-
-
Notifications
You must be signed in to change notification settings - Fork 214
/
reflection.go
57 lines (52 loc) · 1.3 KB
/
reflection.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
package reflection
import (
"reflect"
)
func Invoke(any interface{}, name string, args ...interface{}) {
params := make([]reflect.Value, len(args))
for i, _ := range args {
params[i] = reflect.ValueOf(args[i])
}
reflect.ValueOf(any).MethodByName(name).Call(params)
}
func GetAllMethods(any interface{}) []string {
var methods []string
anyType := reflect.TypeOf(any)
for i := 0; i < anyType.NumMethod(); i++ {
method := anyType.Method(i)
methods = append(methods, method.Name)
}
return methods
}
func Contains(target interface{}, obj interface{}) bool {
targetValue := reflect.ValueOf(target)
switch reflect.TypeOf(target).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < targetValue.Len(); i++ {
if targetValue.Index(i).Interface() == obj {
return true
}
}
case reflect.Map:
if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
return true
}
}
return false
}
func IContains(target interface{}, obj interface{}) bool {
targetValue := reflect.ValueOf(target)
switch reflect.TypeOf(target).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < targetValue.Len(); i++ {
if targetValue.Index(i).Interface() == obj {
return true
}
}
case reflect.Map:
if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
return true
}
}
return false
}