1 Star 0 Fork 0

yoyofx / reflectx

Create your Gitee Account
Explore and code with more than 6 million developers,Free private repositories !:)
Sign up
This repository doesn't specify license. Without author's permission, this code is only for learning and cannot be used for other purposes.
Clone or download
method_info.go 1.44 KB
Copy Edit Web IDE Raw Blame History
yoyofx authored 2020-07-31 13:33 . 改进函数调用方法
package reflectx
import (
"reflect"
)
// Method Info
type MethodInfo struct {
Name string //Method Name
MethodInfoType reflect.Type //method type
Parameters []MethodParameterInfo //method's Parameters
OutType reflect.Type //function's return type.
}
// IsValid : method is valid
func (method MethodInfo) IsValid() bool {
return true
}
// Invoke : invoke the method with interface params.
func (method MethodInfo) Invoke(instance interface{}, params ...interface{}) []interface{} {
paramsCount := len(params)
//paramsValues := make([]reflect.Value, paramsCount)
var paramsValues []reflect.Value
for idx := 0; idx < paramsCount; idx++ {
paramsValues = append(paramsValues, reflect.ValueOf(params[idx]))
}
return method.InvokeWithValue(reflect.ValueOf(instance), paramsValues...)
}
// InvokeWithValue: invoke the method with value params.
func (method MethodInfo) InvokeWithValue(instance reflect.Value, paramsValues ...reflect.Value) []interface{} {
methodInfoVal := instance.MethodByName(method.Name)
returns := methodInfoVal.Call(paramsValues)
outNum := method.MethodInfoType.NumOut()
results := make([]interface{}, outNum)
if len(returns) > 0 {
for i, res := range returns {
results[i] = res.Interface()
}
}
return results
}
// AsTypeInfo : convert method to TypeInfo
func (method MethodInfo) AsTypeInfo() (TypeInfo, error) {
return GetTypeInfoWithValueType(method.MethodInfoType)
}

Comment ( 0 )

Sign in for post a comment

Go
1
https://gitee.com/yoyofx/reflectx.git
git@gitee.com:yoyofx/reflectx.git
yoyofx
reflectx
reflectx
master

Search