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

huangapple go评论139阅读模式
英文:

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

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

答案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.

huangapple
  • 本文由 发表于 2015年9月18日 18:34:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/32649870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定