package main
import (
"fmt"
"reflect"
)
type Animal struct {
A string `json:"a"`
}
func (m *Animal) Eat() {
fmt.Println("eat", m.A)
}
func main() {
animal := Animal{
A: "test",
}
value := reflect.ValueOf(&animal)
f := value.MethodByName("Eat")
f.Call([]reflect.Value{})
}
带参数:
package main
import (
"fmt"
"reflect"
)
type Animal struct {}
func (m *Animal) Eat(a string, i int) {
fmt.Println("eat", a, i)
}
func main() {
animal := Animal{}
p := make([]reflect.Value, 2)
p[0] = reflect.ValueOf("test")
p[1] = reflect.ValueOf(1)
reflect.ValueOf(&animal).MethodByName("Eat").Call(p)
}
带返回值:
package main
import (
"fmt"
"reflect"
)
type Animal struct{}
func (m *Animal) Eat(a string, i int) (string, int) {
return a, i
}
func main() {
animal := Animal{}
p := make([]reflect.Value, 2)
p[0] = reflect.ValueOf("test")
p[1] = reflect.ValueOf(1)
values := reflect.ValueOf(&animal).MethodByName("Eat").Call(p)
for key, val := range values {
fmt.Printf("%d:%v\n", key, val)
}
}