Ai
1 Star 0 Fork 0

张璐月/reflect_fast

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
reflect_method_test.go 1.38 KB
一键复制 编辑 原始数据 按行查看 历史
张璐月 提交于 2025-05-15 17:21 +08:00 . feat 开发测试完成
package test
import (
"fmt"
"reflect"
"testing"
)
//实现:使用反射调用方法,使用场景rpc服务调用
type FuncInfo struct {
Name string
In []reflect.Type
Out []reflect.Type
Result []any
}
type TestUser struct {
Name string
}
func (u *TestUser) GenerateUserName(firstName, lastName string) (string, error) {
return fmt.Sprintf("%s-%s", firstName, lastName), nil
}
func TestReflectMethod(t *testing.T) {
var u *TestUser
typ := reflect.TypeOf(u)
numMethod := typ.NumMethod()
results := make(map[string]*FuncInfo, numMethod)
for i := 0; i < numMethod; i++ {
method := typ.Method(i)
methodTyp := method.Type
inNum := methodTyp.NumIn()
ps := make([]reflect.Value, 0, inNum)
in := make([]reflect.Type, 0, inNum)
// 第一个参数永远是接收器,类似this的概念
ps = append(ps, reflect.ValueOf(u))
for j := 0; j < inNum; j++ {
inTyp := methodTyp.In(j)
in = append(in, inTyp)
if j > 0 {
ps = append(ps, reflect.Zero(inTyp))
}
}
ret := method.Func.Call(ps)
outNum := methodTyp.NumOut()
out := make([]reflect.Type, 0, outNum)
res := make([]any, 0, outNum)
for k := 0; k < outNum; k++ {
outTyp := methodTyp.Out(k)
out = append(out, outTyp)
res = append(res, ret[k].Interface())
}
results[method.Name] = &FuncInfo{
Name: method.Name,
In: in,
Out: out,
Result: res,
}
}
fmt.Println(results)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/luyue_zhang/reflect_fast.git
git@gitee.com:luyue_zhang/reflect_fast.git
luyue_zhang
reflect_fast
reflect_fast
master

搜索帮助