Go语言提供了 reflect 包来访问程序的反射信息。
package main
import (
"fmt"
"reflect"
)
type P struct {
X int
Y int
}
func main() {
point := P{1, 2}
typeOfPoint := reflect.TypeOf(point)
fmt.Println(typeOfPoint.Name(), typeOfPoint.Kind())
}
输出结果:
P struct
种类(Kind)指的是对象归属的品种,在 reflect 包中有如下定义:
type Kind uint
const (
Invalid Kind = iota // 非法类型
Bool // 布尔型
Int // 有符号整型
Int8 // 有符号8位整型
Int16 // 有符号16位整型
Int32 // 有符号32位整型
Int64 // 有符号64位整型
Uint // 无符号整型
Uint8 // 无符号8位整型
Uint16 // 无符号16位整型
Uint32 // 无符号32位整型
Uint64 // 无符号64位整型
Uintptr // 指针
Float32 // 单精度浮点数
Float64 // 双精度浮点数
Complex64 // 64位复数类型
Complex128 // 128位复数类型
Array // 数组
Chan // 通道
Func // 函数
Interface // 接口
Map // 映射
Ptr // 指针
Slice // 切片
String // 字符串
Struct // 结构体
UnsafePointer // 底层指针
)
任意值通过 reflect.TypeOf()
获得反射对象信息后,如果它的类型是结构体,可以通过反射值对象 reflect.Type
的 NumField()
和 Field()
方法获得结构体成员的详细信息。