0

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

hitsu
  • 3
  • 2

1 Answers1

0

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.

Ainar-G
  • 34,563
  • 13
  • 93
  • 119
  • > m := &Method1{record: "bar"} I need to create instance from methodName, because it shoud work when mehtodName is "Method2". – hitsu Sep 20 '15 at 01:22
  • An instance of what? You [can't just instantiate types from strings](http://stackoverflow.com/questions/23030884/is-there-a-way-to-create-an-instance-of-a-struct-from-a-string). – Ainar-G Sep 20 '15 at 08:28
  • I see. My question is same as the link. Thank you for giving reference. – hitsu Jan 28 '16 at 15:05