一、反射的意义
反射是指程序在运行时自省和分析自己的结构的能力。在golang中,”reflect”包提供了反射需要的所有API。反射通常也被称为元编程。为了理解反射,让我们先从一个空接口入门。
空接口指没有声明任何方法的接口。当我们声明一个包含未知类型的参数的接口时,空接口就非常有用了。库方法如Println,Printf就是使用空接口为参数。空接口拥有的一些隐藏属性赋予它这些功能。数据通过以下方式被抽象。
我们通过一个例子来解释
// Understanding Empty Interfaces in Golangpackage mainimport ("fmt")func observe(i interface{}) {// using the format specifier// %T to check type in interfacefmt.Printf("The type passed is: %T\n", i)// using the format specifier %#v// to check value in interfacefmt.Printf("The value passed is: %#v \n", i)fmt.Println("-------------------------------------")}func main() {var value float64 = 15value2 := "GeeksForGeeks"observe(value)observe(value2)}
以上代码的输出为:
The type passed is: float64The value passed is: 15-------------------------------------The type passed is: stringThe value passed is: "GeeksForGeeks"-------------------------------------
我们可以清楚地看到,空接口能够接收任意参数,适用它的值和数据类型。这包括但不限于结构体和结构体指。
那么我们为什么要使用反射呢?
通常传递给空接口的数据并不是原始类型。它们可能是结构体。我们需要在不知道它们的类型或者它们的值的情况下执行一些逻辑。在这种情况下,为了能够在这些结构体上施加多种操作,比如解析它内部的值来查询数据库,或者创建一个数据库schema,我们需要知道它内部数据的类型和字段的数量。这些问题可以使用反射在运行时处理。
二、reflect 包
go反射的基础基于Value、Type 和 Kind 这三个概念,分别对应reflect包下的三个类型:
reflect.Value, reflect.Type and reflect.Kind,可以通过以下方法获取:
- reflect.ValueOf(x interface{}).
- reflect.TypeOf(x interface{}).
- Type.Kind(). | Type | Kind | | —- | —- | | reflect.Type是对业务类型的描述。例如,在用户自定义的结构体、函数或接口中,结构体(函数、接口)的名称就存储在reflect.Type中。所以reflect.Type是业务类型的元数据。 | reflect.Kind是对reflect.Type的描述。比如用户定义了一个业务类型,如果是结构体类型,那么reflect.TypeOf(custom).Kind()等于reflect.Struct,它是一个枚举值 | | 使用 reflect.TypeOf(x interface{})获取Type | 在Type实例上调用.Kind()方法获取Kind实例 |
reflect包还提供了一些其它的方法:
Number(): 返回一个结构体拥有的字段的数量。如果传递的参数不是结构体,则Panic。
Field():这个方法允许我们通过下标访问结构体中的每个字段。
在下面的例子中,我们将发现Kind和Type的不同
// Example program to show difference between// Type and Kind and to demonstrate use of// Methods provided by Go reflect Packagepackage mainimport ("fmt""reflect")type details struct {fname stringlname stringage intbalance float64}type myType stringfunc showDetails(i, j interface{}) {t1 := reflect.TypeOf(i)k1 := t1.Kind()t2 := reflect.TypeOf(j)k2 := t2.Kind()fmt.Println("Type of first interface:", t1)fmt.Println("Kind of first interface:", k1)fmt.Println("Type of second interface:", t2)fmt.Println("Kind of second interface:", k2)fmt.Println("The values in the first argument are :")if reflect.ValueOf(i).Kind() == reflect.Struct {value := reflect.ValueOf(i)numberOfFields := value.NumField()for i := 0; i < numberOfFields; i++ {fmt.Printf("%d.Type:%T || Value:%#v\n",(i + 1), value.Field(i), value.Field(i))fmt.Println("Kind is ", value.Field(i).Kind())}}value := reflect.ValueOf(j)fmt.Printf("The Value passed in "+"second parameter is %#v", value)}func main() {iD := myType("12345678")person := details{fname: "Go",lname: "Geek",age: 32,balance: 33000.203,}showDetails(person, iD)}
以上代码的输出为:
Type of first interface: main.detailsKind of first interface: structType of second interface: main.myTypeKind of second interface: stringThe values in the first argument are :1.Type:reflect.Value || Value:"Go"Kind is string2.Type:reflect.Value || Value:"Geek"Kind is string3.Type:reflect.Value || Value:32Kind is int4.Type:reflect.Value || Value:33000.203Kind is float64The Value passed in second parameter is "12345678"
在以上例子中,我们给showDetails()函数传递了两个参数:
- person,是一个结构体
- ID,是一个字符串
我们使用reflect.TypeOf(i interface{})和Type.Kind()方法获得那些字段,从输出中可以看出两者的不同:
- person实例的Type为
main.details,Kind为reflect.Struct - 变量iD的Type为
main.myType, Kind 为string
通过对比,Type和Kind的的差异就很清楚了,它们分别对应签名的不同部分。这是go反射的基础概念。我们还使用了reflect.Value()、.NumField()和.Field()方法,分别用于获取空接口变量的值、结构体的字段的数量以及第i个字段。
reflect包中的api罗列如下:
| DeepEqual(x, y interface{}) bool | 比较两个对象是否“深度”相等。及深入到叶子元素相等 |
|---|---|
| MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value | typ必须为function。用于创建一个typ的新实例,及创建一个Type为typ的新函数。当调用这个新函数时,会将参数转换为切片,然后用转换后的切片参数调用fn。这个API可以用于动态代理一个函数实例。 |
| Swapper(slice interface{}) func(i, j int) | 返回一个可用于交换某个切片类型中第i和第j个元素的函数 |
| Type.Align() int | 获取类型的对齐值。关于对齐值的解释参考https://www.cnblogs.com/clover-toeic/p/3853132.html |
| Type.FieldAlign() int | 类型作为结构体的字段时的对齐值 |
| Type.Method(int) Method | 获取类型的第i个方法 |
| Type.MethodByName(string) (Method, bool) | 根据名称获取类型的方法 |
| Type.NumMethod() int | 获取类型的公有方法数量 |
| Type.Name() string | 获取类型的名称 |
| Type.PkgPath() string | 获取类型的包路径,如“encoding/base64” |
| Type.Size() uintptr | 获取存储这个类型的值需要占用多少空间 |
| Type.String() string | 返回一个描述这个类型的字符串 |
| Type.Kind() Kind | 返回这个类型的Kind |
| Type.Implements(u Type) bool | 判断此类型是否实现了另一个接口类型u |
| Type.AssignableTo(u Type) bool | 判断此接口类型是否为被另一个类型u实现 |
| Type.ConvertibleTo(u Type) bool | 判断此类型的值能否转换为类型u |
| Type.Comparable() bool | 判断类型是否为可比较的 |
| Type.Bits() int | 返回类型的bit数。type必须为以下一种:sized or unsized Int, Uint, Float, or Complex kinds |
| Type.ChanDir() ChanDir | 返回通道类型的方向: RecvDir _ChanDir = 1 << iota // <-chan _SendDir // chan<- BothDir = RecvDir | SendDir |
| _Type._IsVariadic() bool | 判断一个函数类型是否包含可变参数 |
| Type.Elem() Type | 获取集合类型的元素的类型,type的Kind必须为以下一种:Array, Chan, Map, Ptr, or Slice. |
| Type.Field(i int) StructField | 获取结构体类型的第i个字段 |
| Type.FieldByIndex(index []int) StructField | 获取结构体类型的深层内嵌字段,index是目标字段路由 |
| Type.FieldByName(name string) (StructField, bool) | 根据名称获取结构体类型的字段 |
| Type.FieldByNameFunc(match func(string) bool) (StructField, bool) | 通过某个函数来筛选结构体字段。该函数根据字段的名称做判断 |
| Type.In(i int) Type | 获取函数类型的第i个入参的类型 |
| Type.Key() Type | 返回一个map类型的key的类型 |
| Type.Len() int | 返回数组类型的长度 |
| Type.NumField() int | 获取结构体类型的字段数量 |
| Type.NumIn() int | 获取函数类型的入参个数 |
| Type.NumOut() int | 获取函数类型的出参个数 |
| Type.Out(i int) Type | 获取函数类型第i个出参的类型 |
| (m Method) IsExported() bool | 判断方法是否为公有 |
| (k Kind) String() string | 返回Kind的名称 |
| (f StructField) IsExported() bool | 判断结构体字段是否为公有 |
| (tag StructTag) Get(key string) string | 获取某个结构体字段tag中某个key对应的值,如果不存在,则为空字符串 |
| (tag StructTag) Lookup(key string) (value string, ok bool) | 与上一个的区别是,可以判断是否存在(上一个api不能知晓返回的空串是tag值还是值不存在) |
| TypeOf(i interface{}) Type | 获取某个对象的类型 |
| PtrTo(t Type) Type | 返回类型t对应的指针类型。比如,t代表类型Foo,那么PtrTo(t)返回值代表*Foo |
| MapOf(key, elem Type) Type | 根据key和值的类型,返回一个map类型 |
| FuncOf(in, out []Type, variadic bool) Type | 根据输入输出参数的类型,以及最后一个入参是否可变,返回一个函数类型 |
| SliceOf(t Type) Type | 创建一个元素类型为t的切片类型 |
| StructOf(fields []StructField) Type | 根据字段定义,创建一个结构体类型 |
| ArrayOf(length int, elem Type) Type | 根据长度和元素类型,创建一个数组类型 |
| (v Value) Addr() Value | 返回代表Value地址的指针Value |
| (v Value) Bool() bool | 返回Value底层的布尔值,如果Kind不为bool,则panic |
| (v Value) Bytes() []byte | 返回底层的字节数组 |
| (v Value) CanAddr() bool | 判断能否通过Addr()方法获取地址指针 |
| (v Value) CanSet() bool | 判断此Value底层的值能否被更改 |
| (v Value) Call(in []Value) []Value | 调用函数类Value |
| (v Value) CallSlice(in []Value) []Value | 调用拥有可变入参的函数类Value |
| (v Value) Close() | 通道类Value,关闭通道 |
| (v Value) Complex() complex128 | 返回底层复数 |
| (v Value) Elem() Value | 返回接口类型Value指向的实际结构体类型Value,或者返回指针类型Value对应的结构体类型Value |
| (v Value) Field(i int) Value | 获取结构体类型Value第i个字段的Value |
| (v Value) FieldByIndex(index []int) Value | 获取结构体类型Value深层内嵌字段的Value |
| (v Value) FieldByName(name string) Value | |
| (v Value) FieldByNameFunc(match func(string) bool) Value | |
| (v Value) Float() | |
| (v Value) Index(i int) Value | 获取第i个元素的Value,v必须为以下Kind:Array, Slice, or String |
| (v Value) Int() int64� | |
| (v Value) CanInterface() bool | 判读 Interface() API是否可以调用得通,而不panic |
| (v Value) Interface() (i interface{}) | 返回Value底层值,可以用interface{}类型变量接收 |
| (v Value) IsNil() bool | 判断是否为空值 |
| (v Value) IsValid() bool | 判断Value是否有效地代表了一个值。如果v代表零值,则返回false。如果这个方法返回false(v不一定为零值),那么其它一系列方法都会panic,除了String()方法 |
| (v Value) IsZero() bool | 判断Value是否代表对应Type的零值。如果IsValid()返回false,那么此方法panic |
| (v Value) Kind() Kind | 返回Value的Kind |
| (v Value) Len() int | 返回长度,Value的Kind必须为以下之一:Array, Chan, Map, Slice, or String |
| (v Value) MapIndex(key Value) Value | 返回map类型Value中,key对应的值Value |
| (v Value) MapKeys() []Value | 返回map类型value的所有key值 |
| (v Value) MapRange() *MapIter | 获取map类型Value的迭代器 |
| (it *MapIter) Key() Value | 获取map迭代器当前key |
| (it *MapIter) Value() Value | 获取map迭代器当前value |
| (it *MapIter) Next() bool | 判断迭代器是否有下一个值 |
| (v Value) Method(i int) Value | 返回v的第i个方法,返回值的Kind为function |
| (v Value) NumMethod() int | |
| (v Value) MethodByName(name string) Value | |
| (v Value) NumField() int | |
| (v Value) OverflowComplex(x complex128) bool � |
判断v的Kind能否用来接收x。如果v的Kind为complex128,那么肯定可以接收x,不会溢出,返回false。如果v的Kind为complex64,则有可能溢出,取决于x的具体大小,是否超过complex64最大值 |
| (v Value) OverflowFloat(x float64) bool | |
| (v Value) OverflowInt(x int64) bool | |
| (v Value) OverflowUint(x uint64) bool | |
| (v Value) Pointer() uintptr | 以指针形式返回v的值 |
| (v Value) Recv() (x Value, ok bool) | 从通道获取值 |
| (v Value) Send(x Value) | 往通道发送值 |
| (v Value) Set(x Value) | 将x设置到v,如果CanSet返回false,此方法panic |
| (v Value) SetBool(x bool) | |
| (v Value) SetBytes(x []byte) | |
| (v Value) SetComplex(x complex128) | |
| (v Value) SetFloat(x float64) | |
| (v Value) SetInt(x int64) | |
| (v Value) SetLen(n int) | 设置切片的长度 |
| (v Value) SetCap(n int) | 设置切片的容量 |
| (v Value) SetMapIndex(key, elem Value) | 往map添加kv |
| (v Value) SetMapIndex(key, elem Value) | |
| (v Value) SetPointer(x unsafe.Pointer) | |
| (v Value) SetString(x string) | |
| (v Value) Slice(i, j int) Value | 获取切片Value,v的Kind必须为Array, Slice or String |
| (v Value) String() string | 返回v的string值。v的Kind不限于string |
| (v Value) TryRecv() (x Value, ok bool) | 非阻塞式从通道获取值 |
| (v Value) TrySend(x Value) bool | 非阻塞式往通道发送值 |
| (v Value) Type() Type | 返回v的Type |
| (v Value) Uint() uint64 | 返回底层的uint64值 |
| (v Value) UnsafeAddr() uintptr | 返回v的数据的指针 |
| Append(s Value, x …Value) Value | 往切片追加元素,并返回新的切片 |
| AppendSlice(s, t Value) Value | 往切片追加切片,返回新的切片 |
| Copy(dst, src Value) int | 拷贝元素。dst必须为Slice or Array |
| Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) | 对多个通道执行select操作。通道的读取、发送在cases中定义 |
| MakeSlice(typ Type, len, cap int) Value | 创建切片 |
| MakeChan(typ Type, buffer int) Value | |
| MakeMap(typ Type) Value | |
| MakeMapWithSize(typ Type, n int) Value | |
| Indirect(v Value) Value | 返回v指向的值。如果v不为指针,则返回v本身。如果v为nil指针,则返回零值 |
| ValueOf(i interface{}) Value | |
| Zero(typ Type) Value | 返回零值 |
| New(typ Type) Value | 返回零值指针 |
| NewAt(typ Type, p unsafe.Pointer) Value | 返回零值指针,并用p作为那个指针 |
| (v Value) Convert(t Type) Value | 将v转换为t类型的值 |
| (v Value) CanConvert(t Type) bool | 判断能否将v转换为t类型的值 |
| VisibleFields(t Type) []StructField | 返回t中的可见字段。如果一个字段可以通过FieldByName方法获取,那么它就是可见的。 |
