01
概念
在 Go 语言中,reflect 可以用来在运行期间获取对象的类型信息和内存结构,reflect 操作所需的全部信息都源自接口变量,接口变量除了存储自身类型外,还会保存实际对象的类型数据。reflect 通过 TypeOf 和 ValueOf 函数,将任何传入的对象转换为接口类型。
02
使用反射获取对象的类型
TypeOf returns the reflection Type that represents the dynamic type of i. If i is a nil interface value, TypeOf returns nil.
func reflect.TypeOf(i interface{}) reflect.Type
输出结果:
go run main.go
A int
需要注意的是,Name 是真实类型,Kind 是真实类型的基础结构类别。在类型判断时要注意区分。
示例代码:
输出结果:
go run main.go
int *int false int
int ptr
true
代码中,我们使用 Elem 方法返回指针的基类型,此外,Elem 方法还可以返回数组、slice、map、chan 的基类型。
03
使用反射操作 struct
输出结果: go run main.go 2 name string score int
输出结果: go run main.go name user_name age user_age
04
使用反射获取和修改对象的值
ValueOf returns a new Value initialized to the concrete value stored in the interface i. ValueOf(nil) returns the zero Value.
func reflect.ValueOf(i interface{}) reflect.Value
示例代码:
输出结果:
go run main.go
v:{ 0} type:main.animal kind:struct
v:{kity 0} type:main.animal kind:struct
通过代码演示,发现 ValueOf 可以获取对象的值。
我们知道修改对象的变量,需要传入指针,但是因为接口变量存储的指针是不可以寻址和设置变量的,所以还需要通过 Elem 获取目标对象。
非导出字段的值不能修改。
05
使用反射动态调用方法
输出结果: go run main.go 姓名:frank 积分:88
输出结果: go run main.go [I am lucy, My hobby is [singing dancing]] [I am lucy, My hobby is [singing dancing]]