英文:
Golang: How can I use refect package with exsisting library
问题
我想从函数名中调用现有库中的一个函数。
在Go语言中,只需通过方法名调用方法即可,因为reflect包中有(v Value) MethodByName(name string)方法。但是,为了调用一个方法,所有方法的参数都应该是reflect.Value类型。
我该如何调用参数不是reflect.Value类型的函数?
package main
//-------------------------------
// 现有库的示例
//-------------------------------
type Client struct {
    id string
}
type Method1 struct {
    record string
}
// type Method2 struct{}
// ...
// 在库中定义:不要更改
func (c *Client) Method1(d *Method1) {
    d.record = c.id
}
//------------------
// 从这里开始编辑
//------------------
func main() {
    // 从命令行获取MethodN
    method_name := "Method1"
    // 我该如何正确调用Method1(*Method1)函数?
    // * 创建Method1实例
    // * 调用Method1函数
    // ...
    //fmt.Printf("%s record is %s", method_name, d.record)
}
http://play.golang.org/p/6B6-90GTwc
英文:
I want to call a function in a existing library from function name.
In golang, just calling method from methodname is OK, because reflect package has (v Value) MethodByName(name string).
But, for calling a method, all method argument should be reflect.Value.
How can I call a function whose argument are not reflect.Value.
package main
//-------------------------------
// Example of existing library
//-------------------------------
type Client struct {
	id string
}
type Method1 struct {
	record string
}
// type Method2 struct{}
// ...
// defined at library : do not change
func (c *Client) Method1(d *Method1) {
	d.record = c.id
}
//------------------
// Edit from here
//------------------
func main() {
	// give MethodN from cmd line
	method_name := "Method1"
	// How can I call Method1(* Method1) propery???
	// * Make Method1 instance
	// * Call Method1 function
	//...
	//fmt.Printf("%s record is %s", method_name, d.record)
}
答案1
得分: 0
你需要使用reflect.ValueOf来获取客户端和方法值的reflect.Value,然后使用reflect.Value.Call方法:
methodName := "Method1"
c := &Client{id: "foo"}
m := &Method1{record: "bar"}
args := []reflect.Value{reflect.ValueOf(m)}
reflect.ValueOf(c).MethodByName(methodName).Call(args)
fmt.Printf("%s record is %s", methodName, m.record)
Playground: http://play.golang.org/p/PT33dqj9Q9.
英文:
You need to get reflect.Values of client and method values with reflect.ValueOf and then use reflect.Value.Call:
methodName := "Method1"
c := &Client{id: "foo"}
m := &Method1{record: "bar"}
args := []reflect.Value{reflect.ValueOf(m)}
reflect.ValueOf(c).MethodByName(methodName).Call(args)
fmt.Printf("%s record is %s", methodName, m.record)
Playground: http://play.golang.org/p/PT33dqj9Q9.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论