mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-11 01:23:51 +00:00
e2ab363e64
Signed-off-by: c9s <yoanlin93@gmail.com>
42 lines
932 B
Go
42 lines
932 B
Go
package dynamic
|
|
|
|
import (
|
|
"errors"
|
|
"reflect"
|
|
)
|
|
|
|
// CallStructFieldsMethod iterates field from the given struct object
|
|
// check if the field object implements the interface, if it's implemented, then we call a specific method
|
|
func CallStructFieldsMethod(m interface{}, method string, args ...interface{}) error {
|
|
rv := reflect.ValueOf(m)
|
|
rt := reflect.TypeOf(m)
|
|
|
|
if rt.Kind() != reflect.Ptr {
|
|
return errors.New("the given object needs to be a pointer")
|
|
}
|
|
|
|
rv = rv.Elem()
|
|
rt = rt.Elem()
|
|
|
|
if rt.Kind() != reflect.Struct {
|
|
return errors.New("the given object needs to be struct")
|
|
}
|
|
|
|
argValues := ToReflectValues(args...)
|
|
for i := 0; i < rt.NumField(); i++ {
|
|
fieldType := rt.Field(i)
|
|
|
|
// skip non-exported fields
|
|
if !fieldType.IsExported() {
|
|
continue
|
|
}
|
|
|
|
if _, ok := fieldType.Type.MethodByName(method); ok {
|
|
refMethod := rv.Field(i).MethodByName(method)
|
|
refMethod.Call(argValues)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|