简介 golang有反射特性。这篇文章用于说明这块的工作。反射机制能将给数据的类型(Type)和值(Value)读取出来。并且能读取出一个struct中的全部的成员。在使用这些的时候。需要稍微注意一下效率。
语法 获取类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 package mainimport ( "reflect" "fmt" ) type lx interface { SayHi() } type User struct { Name string Age int64 Sex string } func (u *User) SayHi() { fmt.Println("hello world" ) } func main () { user := User{"张三" , 25 , "男" } FillStruct(user) } func FillStruct (obj interface {}) { t := reflect.TypeOf(obj) fmt.Println(t.Name()) fmt.Println(t.Kind().String()) fmt.Println(t.PkgPath()) fmt.Println(t.String()) fmt.Println(t.Size()) fmt.Println(t.Align()) fmt.Println(t.FieldAlign()) var u User fmt.Println(t.AssignableTo(reflect.TypeOf(u))) fmt.Println(t.ConvertibleTo(reflect.TypeOf(u))) fmt.Println(t.NumField()) fmt.Println(t.Field(0 ).Name) fmt.Println(t.FieldByName("Age" )) fmt.Println(t.FieldByIndex([]int {0 })) }
获取值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 package mainimport ( "reflect" "fmt" ) type User struct { Name string Age int Sex bool Phone *string Qian float64 Atest uint Group interface {} Btest interface {} } func (u *User) Hello() { fmt.Println("hello world 你好世界" ) } func main () { a := "hello world 你好世界" user := &User{"张三" , 25 , true , &a, 88.8 , 9 , 99 , nil } var obj interface {} = user v := reflect.ValueOf(obj) method := v.MethodByName("Hello" ) method.Call([]reflect.Value{}) fmt.Println(v.IsValid()) fmt.Println(v.Kind()) fmt.Println(v.Type()) v = v.Elem() var u User fmt.Println(v.Convert(reflect.TypeOf(u)).FieldByName("Name" )) fmt.Println(v.FieldByName("Name" ).CanSet()) v.FieldByName("Name" ).SetString("把Name值修改一下" ) v.FieldByName("Name" ).Set(reflect.ValueOf(a)) fmt.Println(v.FieldByName("Group" ).Elem()) fmt.Println(v.FieldByName("Phone" ).Elem()) fmt.Println(v.FieldByName("Name" ).Interface()) fmt.Println(v.FieldByName("Name" ).String()) fmt.Println(v.FieldByName("Sex" ).Bool()) fmt.Println(v.FieldByName("Age" ).Int()) var x int64 fmt.Println(v.FieldByName("Age" ).OverflowInt(x)) fmt.Println(v.FieldByName("Atest" ).Uint()) var x2 uint64 fmt.Println(v.FieldByName("Atest" ).OverflowUint(x2)) fmt.Println(v.FieldByName("Qian" ).Float()) var x3 float64 fmt.Println(v.FieldByName("Qian" ).OverflowFloat(x3)) fmt.Println(v.FieldByName("Btest" ).IsNil()) fmt.Println(v.NumField()) fmt.Println(v.Field(0 )) fmt.Println(v.FieldByIndex([]int {0 })) }
参考 [1] golang reflect