-
Notifications
You must be signed in to change notification settings - Fork 51
/
bean.go
114 lines (87 loc) · 2.14 KB
/
bean.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
package aop
import (
"reflect"
"github.com/gogap/errors"
)
type Bean struct {
id string
class string
instance interface{}
}
func NewBean(id string, instance interface{}) (bean *Bean, err error) {
if id == "" {
err = ErrBeanIDShouldNotBeEmpty.New()
return
}
if instance == nil {
err = ErrBeanInstanceIsNil.New(errors.Params{"id": id})
return
}
v := reflect.ValueOf(instance)
if v.Kind() != reflect.Ptr {
err = ErrBeanIsNotAnPtr.New(errors.Params{"id": id})
return
}
class := ""
if class, err = getFullStructName(instance); err != nil {
return
}
bean = &Bean{
id: id,
class: class,
instance: instance,
}
return
}
func (p *Bean) ID() string {
return p.id
}
func (p *Bean) Class() string {
return p.class
}
func (p *Bean) methodMetadata(methodName string) (metadata MethodMetadata, err error) {
beanType := reflect.TypeOf(p.instance)
var method reflect.Method
exist := false
if method, exist = beanType.MethodByName(methodName); !exist {
err = ErrBeanMethodNotExit.New(errors.Params{"id": p.id, "class": p.class, "method": methodName})
return
}
metadata, err = getMethodMetadata(method)
return
}
func (p *Bean) Invoke(methodName string, args Args, callback ...interface{}) (returnFunc func(), err error) {
var beanValue reflect.Value
beanValue = reflect.ValueOf(p.instance)
inputs := make([]reflect.Value, len(args))
for i := range args {
inputs[i] = reflect.ValueOf(args[i])
}
values := beanValue.MethodByName(methodName).Call(inputs)
if values != nil && len(values) > 0 {
lastV := values[len(values)-1]
if lastV.Interface() != nil {
if errV, ok := lastV.Interface().(error); ok {
if errV != nil {
err = errV
return
}
}
}
}
if callback != nil && len(callback) > 0 {
returnFunc = func() {
reflect.ValueOf(callback[0]).Call(values)
}
}
return
}
func (p *Bean) Call(methodName string, args Args) []reflect.Value {
var beanValue reflect.Value
beanValue = reflect.ValueOf(p.instance)
inputs := make([]reflect.Value, len(args))
for i := range args {
inputs[i] = reflect.ValueOf(args[i])
}
return beanValue.MethodByName(methodName).Call(inputs)
}