Golang:如何将反射包与现有库一起使用

Golang: How can I use refect package with exsisting library

我想从函数名调用现有库中的函数。

在golang中,只要从methodname调用方法就可以了,因为reflect package有(v Value) MethodByName(name string)。 但是,对于调用方法,所有方法参数都应该是 reflect.Value.

如何调用参数不是 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)
}

http://play.golang.org/p/6B6-90GTwc

您需要使用 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)

游乐场:http://play.golang.org/p/PT33dqj9Q9.