如何在Golang中反映对象的动态方法名称

时间:2016-01-28 18:44:42

标签: reflection go

例如

router.Get(path, handler) // works fine

methodStr = "Get"    
router.methodStr(path, handler) // error

funcs := map[string]func(){"methodStr": "Get"}
router.funcs["methodStr"](path, handler) // error

reflect.ValueOf(router).MethodByName("Get").Call([]reflect.Value{}) // error

我将方法名称作为字符串。如何使用字符串名称

调用路由器对象方法

1 个答案:

答案 0 :(得分:1)

你遇到的前两个错误无效Go,所以我不确定你对它们的期望是什么。使用reflect的最后一个示例没有任何需要2的函数的参数,这会引起恐慌。添加2个参数可以正常工作:

http://play.golang.org/p/mSziWdW0hn

args := []reflect.Value{
    reflect.ValueOf("path"),
    reflect.ValueOf("handler"),
}
reflect.ValueOf(router).MethodByName("Get").Call(args)