go - 如何通过字符串变量调用方法?
问题描述
我以前在这里看到过这个问题。但我不明白答案。
如何从字符串值调用方法。所以如果
我有很多方法是
func (c *something) whateverName(whatever map[string]interface{}) {
}
每个参数类型相同。没有回报等......从字面上看,方法名称的唯一区别。
我想做这样的事情,但我无法让它工作。我只想从“var myMethod string”的值中调用正确的方法:
func (c something) foo(m map[string]interface{}) {
fmt.Println("foo..")
//do something with m
}
func main() {
myMethod := "foo"
message := make(map[string]interface{})
//fill message with stuff...
c := something{} //this is just a hypothetical example...
vt := reflect.ValueOf(c)
vm := vt.MethodByName(myMethod)
vm.Call([]reflect.Value{reflect.ValueOf(message)})
}
我显然不明白反射是如何工作的。
解决方案
如果您导出该方法,则您的示例有效。更改foo
为Foo
:
type something struct{}
func (c something) Foo(m map[string]interface{}) {
fmt.Println("Foo..")
//do something with m
}
func main() {
myMethod := "Foo"
message := make(map[string]interface{})
//fill message with stuff...
c := something{} //this is just a hypothetical example...
vt := reflect.ValueOf(c)
vm := vt.MethodByName(myMethod)
vm.Call([]reflect.Value{reflect.ValueOf(message)})
}
这将输出(在Go Playground上尝试):
Foo..
另请注意,在此示例Foo()
中具有 value receiver: c something
。如果方法有指针接收器如c *something
,则需要有一个指针值开头,因为带有指针接收器的方法不在非指针类型的方法集中。
参见相关:调用具有特殊前缀/后缀的函数
推荐阅读
- java - 具有一个命名空间和本地部分的多个 SOAP 端点
- c# - 如何从 SQLite 数据库的新记录中获取具有 char 数据类型的字段,它也由使用 dapper + c# 的触发器生成
- jquery - 如何在 jQuery 对象中使用“自我”?
- jquery - 使用 JQuery 构建选项卡
- python - How to execute query formed by python-sql query builder?
- c++ - 从类的 QList 访问受保护的成员,例如 QList
- python - 将逻辑字符串转换为 JSON
- visual-studio - 如何防止 Visual Studio 以只读模式打开文件?
- google-sheets - 条件格式检查每一列
- multithreading - 对于扫描音频插件,我需要在 QT 中使用哪种类型的线程模型?