package main
import (
"fmt"
"reflect"
"strings"
)
type A struct {
b string
c string
d string
}
func (a *A) GetB() string {
return a.b
}
func (a *A) GetC() string {
return a.c
}
func (a *A) GetD() string {
return a.d
}
func main() {
a := &A{}
a.b = "we get b!"
a.c = "we get c!"
a.d = "we get d!"
v := reflect.TypeOf(a).Elem()
ac := reflect.ValueOf(a)
for index:=0;index<v.NumField();index++{
methodName := "Get"+strings.ToUpper(v.Field(index).Name)
method := ac.MethodByName(methodName)
c := method.Call(nil)
result := c[0].String()
fmt.Printf("%d: %s\n",index,result)
}
}
运行结果
0: we get b!
1: we get c!
2: we get d!
参考链接(包看包会):