package main import ( "fmt" "reflect" ) type User struct { Id int Name string Age int } func (u User) ReflectCallFunc(s string) { fmt.Println("test ok ", s) } func Do(input interface{}) { getType := reflect.TypeOf(input) //TypeOf获取变量的类型。如:int、string、struct fmt.Println("get Type is:", getType.Name()) getValue := reflect.ValueOf(input) //ValueOf获取变量的值,结构体上绑定的函数属于<值> fmt.Println("get all fields is :", getValue) // 获取方法字段 // 1. 先获取interface的reflect.Type,然后通过NumField进行遍历 // 2. 再通过reflect.Type的Field获取其Field // 3. 最后通过Field的Interface()得到对应的value for i:=0; i<getType.NumField(); i++ { field := getType.Field(i) value := getValue.Field(i) fmt.Printf("%s:%v = %v\n", field.Name, field.Type, value) } // 获取方法 // 1. 先获取interface的reflect.Type,然后通过.NumMethod进行遍历 for i:=0; i<getType.NumMethod();i++ { m := getType.Method(i) fmt.Printf("%s:%v\n", m.Name, m.Type) } // 2. 直接调用方法[使用reflect.ValueOf()来调用函数] methodValue := getValue.MethodByName("ReflectCallFunc") //args := make([]reflect.Value, 0) args := []reflect.Value{reflect.ValueOf("Done")} methodValue.Call(args) } func main() { user := User{1, "Fan", 30} Do(user) } //get Type is: User //get all fields is : {1 Fan 30} //Id:int = 1 //Name:string = Fan //Age:int = 30 //ReflectCallFunc:func(main.User, string) //test ok Done