doudandui1592 2015-09-18 10:34
浏览 24
已采纳

Golang:如何在现有库中使用反射包

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)
}

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

  • 写回答

1条回答 默认 最新

  • dtl85148 2015-09-18 11:57
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器