在结构方法内部使用反射调用结构的方法

How can I use reflect to call method of struct, inside a struct method? e.g:

package main

import "fmt"
import "reflect"

type T struct{}

func (t *T) New() {
    value := getDynamicValue()
    method := reflect.ValueOf(&t).MethodByName(value)
    fmt.Println(method)
}

func (t *T) fake() {
    fmt.Println("Fake!")
}

func main() {
    var t T
    t.New()
}

func getDynamicValue() string {
    return "fake"
}

The following code will print <invalid reflect.Value> even though fake exists.

Thanks in advance! :)

The problems are that:

  • &t is passed to ValueOf instead of t
  • the fake method is not exported

Here is a working example:

package main

import "fmt"
import "reflect"

type T struct{}

func (t *T) New() {
    value := getDynamicValue()
    method := reflect.ValueOf(t).MethodByName(value)
    fmt.Println(method)
}

func (t *T) Method() {
    fmt.Println("Hello world!")
}

func main() {
    var t T
    t.New()
}

func getDynamicValue() string {
    return "Method"
}

Outputs

0xec820

Try it yourself

You need to export the method and call it:

package main

import "fmt"
import "reflect"

type T struct{}

func (t *T) New() {
    value := getDynamicValue()
    method := reflect.ValueOf(t).MethodByName(value)
    fmt.Println(method.Call(nil))
}

func (t *T) Fake() {
    fmt.Println("Fake!")
}

func main() {
    var t T
    t.New()
}

func getDynamicValue() string {
    return "Fake"
}