call func by string in golang

案例一

package main

import (
	"fmt"
	"reflect"
)

type My struct{}

func (m My) MyFunc(s string) {
	fmt.Println("MyFunc called")
	fmt.Println(s)
}

func main() {
	m := My{}
	meth := reflect.ValueOf(m).MethodByName("MyFunc")
	meth.Call(nil, "aa")
}

案例二

package main

import (
	"fmt"
	"reflect"
)

type My struct{}

func (m My) MyFunc() {
	fmt.Println("MyFunc called")
}

func main() {
	registry := map[string]func() interface{}{
		"My": func() interface{} { return My{} },
	}

	v := registry["My"]()
	meth := reflect.ValueOf(v).MethodByName("MyFunc")
	meth.Call(nil)
}

案例三

package main

import (
	"fmt"
	"reflect"
)

type T struct{}

func (t *T) Foo() {
	fmt.Println("foo")
}

type MyStruct struct {
	id int
}

type Person struct {
	Name string
	Age  int
}

func (t *T) Bar(ms *MyStruct, p *Person) int {
	return p.Age

}

func main() {
	var t *T
	reflect.ValueOf(t).MethodByName("Foo").Call([]reflect.Value{})
	var ans int64
	ans = reflect.ValueOf(t).MethodByName("Bar").Call([]reflect.Value{reflect.ValueOf(&MyStruct{15}), reflect.ValueOf(&Person{"Dexter", 15})})[0].Int()
	fmt.Println(ans)
}