Reflection 戈兰:我如何使用现有库的refect包

Reflection 戈兰:我如何使用现有库的refect包,reflection,go,Reflection,Go,我想从函数名调用现有库中的函数 在golang中,只从methodname调用方法是可以的,因为reflect包具有(v值)MethodByName(名称字符串)。 但是,对于调用方法,所有方法参数都应该是reflect.Value package main //------------------------------- // Example of existing library //------------------------------- type Client struct {

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

在golang中,只从methodname调用方法是可以的,因为reflect包具有(v值)MethodByName(名称字符串)。 但是,对于调用方法,所有方法参数都应该是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)
}
如何调用参数不是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)
}

您需要使用
reflect.ValueOf
获取客户端的
reflect.Value
s和方法值,然后使用
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)

操场:。

>m:=&Method1{record:“bar”}我需要从methodName创建实例,因为当methodName是“Method2”时它应该工作。什么的实例?你,我明白了。我的问题和链接一样。谢谢你的推荐。