13 反射reflection

反射可大大提高程序的灵活性,使得 interface{} 有更大的发挥余地
反射使用 TypeOf 和 ValueOf 函数从接口中获取目标对象信息
反射会将匿名字段作为独立字段(匿名字段本质)
想要利用反射修改对象状态,前提是 interface.data 是 settable,
即 pointer-interface

  • 通过反射可以“动态”调用方法

type User struct {
Id int
Name string
Age int
}

func (u User) Hello() {

}

func main() {
u := User{1 , "OK", 12}
Info(u)
// Type:User
// fields:
//Id: int 1
//Name: string OK
//Age: int 12
//Hello:func(main.User) //hello方法 类型是函数main包下面的函数
}

func Info(o interface{}) {
t := reflect.TypeOf(o)
fmt.Println("Type:", t.Name())

v :=reflect.ValueOf(o)
fmt.Println("fields:")

for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
val := v.Field(i).Interface()
fmt.Println("%6s: %v = %v", f.Name, f.Type, val)
}

for i :=0; i < t.NumMethod(); i++ {
m := t.Method(i)
fmt.Printf("%6s: %v\n", m.Name, m.Type) //方法名
}

}

你可能感兴趣的:(13 反射reflection)