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
fake
method is not exportedHere 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
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"
}