golang中的反射
Go语言中的变量是分为两部分的:类型信息:预先定义好的元信息。值信息:程序运行过程中可动态变化的。
2.反射介绍
在Python中,Java中,都有反射的概念。反射是"指程序运行期对程序本身进行访问和修改的能力"。程序在编译时,变量被转换为内存地址,变量名不会被编译器写入到可执行部分。在运行程序时,程序无法获取自身的信息。支持反射的语言,可以再程序编译期将变量的反射信息,如字段名称、类型信息、结构体信息等正和岛可执行文件中,并给程序提供接口,访问反射信息,这样就可以在程序运行期获取类型的反射信息,并且有能力修改它们。Go程序在运行期使用reflect包访问程序的反射信息。上面我们介绍过空接口,空接口可以存储任意类型的变量,那我们怎样知道空接口保存的数据是什么呢?"反射就是在运行时动态的获取一个变量的类型信息和值信息。"
3.reflect包
在Go语言的反射机制中,任何接口都由"一个具体类型"和"具体类型的值"两部分组成。在Go语言中反射的相关功能由内置的reflect包提供,任意接口值在反射中都可以理解为由reflect.Type和reflect.Value两部分组成,并且reflect包提供了reflect.TypeOf和reflect.ValueOf两个函数来获取任意对象的Value和Type。
3.1TypeOf
在Go语言中,使用reflect.TypeOf()函数可以获得任意值的类型对象(reflect.Type),程序通过类型对象可以访问任意值的类型信息。
package mainimport ( "fmt" "reflect")func reflectType(x interface{}) { v := reflect.TypeOf(x) fmt.Printf("type:%v\n",v)}func main() { var a float32 = 3.14 reflectType(a) var b int32 = 100 reflectType(b)}结果:type:float32type:int32Process finished with exit code 0
3.2type name和type kind
在反射中关于类型,还划分为两种:类型(Type)和种类(Kind)。因为在Go语言中我们可以使用type关键字构造很多自定义类型,而种类(Kind)就是指底层的类型,,在反射中,当需要区分int,map,指针,结构体等大品种的类型时,就会用到种类(Kind)。
reflect包中定义的Kind类型如下:type Kind uintconst ( 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 // 底层指针)
定义两个指针类型和两个结构体类型,通过反射来看它们的类型和种类。package mainimport ( "fmt" "reflect")type Myint int64func reflectType(x interface{}) { v := reflect.TypeOf(x) //Go语言的反射中,数组、切片、map、指针等类型的变量,它们的.Name都是返回空 fmt.Printf("type:%v Kind:%v\n",v.Name(),v.Kind())}func main() { var a *float32 //指针 var b map[string]string //map var c Myint //自定义类型 var d rune //类型别名 type person struct { name string } reflectType(a) //type: Kind:ptr reflectType(b) //type: Kind:map reflectType(c) //type:Myint Kind:int64 reflectType(d)//type:int32 Kind:int32 var p = person{name:"lili"} reflectType(p) //type:person Kind:struct}结果:type: Kind:ptrtype: Kind:maptype:Myint Kind:int64type:int32 Kind:int32type:person Kind:structProcess finished with exit code 0
3.3ValueOf
reflect.ValueOf()返回的是reflect.Value类型,其中包含了原始值的值信息。reflect.Value与原始值之间可以互相转换。reflect.Value类型提供了获取原始值的方法如下:
package mainimport ( "fmt" "reflect")func reflectValue(x interface{}) { v := reflect.ValueOf(x) k := v.Kind() switch k { case reflect.Int64: // v.Int()从反射中获取整型的原始值,然后通过int64()强制类型转换 fmt.Printf("type is int64, value is %d\n", int64(v.Int())) case reflect.Float32: // v.Float()从反射中获取浮点型的原始值,然后通过float32()强制类型转换 fmt.Printf("type is float32, value is %f\n", float32(v.Float())) case reflect.Float64: // v.Float()从反射中获取浮点型的原始值,然后通过float64()强制类型转换 fmt.Printf("type is float64, value is %f\n", float64(v.Float())) }}func main() { var a float32 = 3.14 var b int64 = 100 reflectValue(a) //type is float32, value is 3.140000 reflectValue(b) //type is int64, value is 100 //将int类型的原始值转换为reflect.Value类型 c := reflect.ValueOf(10) fmt.Println("type c:%T\n",c)}结果:type is float32, value is 3.140000type is int64, value is 100type c:%T 10Process finished with exit code 0
3.5通过反射设置变量的值
想要在函数中通过反射修改变量的值,需要注意函数参数传递的是值拷贝,必须传递变量地址才能修改变量值。反射中使用Elem()方法获取指针对应的值。
package mainimport ( "fmt" "reflect")func reflectSetValue1(x interface{}) { v:=reflect.ValueOf(x) if v.Kind() == reflect.Int64{ v.SetInt(200) //修改的是副本,reflect包会引发panic }}func reflectSetValue2(x interface{}) { v:=reflect.ValueOf(x) //反射中使用Element()方法获取指针对应的值 if v.Elem().Kind() == reflect.Int64{ v.Elem().SetInt(200) }}func main() { var a int64 = 100 //reflectSetValue1(a) ////panic: reflect: reflect.Value.SetInt using unaddressable value reflectSetValue2(&a) fmt.Println(a) //200}结果:200Process finished with exit code 0
3.6isNil()和isValid()
IsNil()常被用于判断指针是否为空;IsValid()常被用于判定返回值是否有效。
isNil()func (v Value) IsNil() boolIsNil()报告v持有的值是否为nil。v持有的值的分类必须是通道、函数、接口、映射、指针、切片之一;否则IsNil函数会导致panic。isValid()func (v Value) IsValid() boolIsValid()返回v是否持有一个值。如果v是Value零值会返回假,此时v除了IsValid、String、Kind之外的方法都会导致panic。
package mainimport ( "fmt" "reflect")func main() { // *int类型空指针 var a *int fmt.Println("var a *int IsNil:", reflect.ValueOf(a).IsNil()) // nil值 fmt.Println("nil IsValid:", reflect.ValueOf(nil).IsValid()) // 实例化一个匿名结构体 b := struct{}{} // 尝试从结构体中查找"abc"字段 fmt.Println("不存在的结构体成员:", reflect.ValueOf(b).FieldByName("abc").IsValid()) // 尝试从结构体中查找"abc"方法 fmt.Println("不存在的结构体方法:", reflect.ValueOf(b).MethodByName("abc").IsValid()) // map c := map[string]int{} // 尝试从map中查找一个不存在的键 fmt.Println("map中不存在的键:", reflect.ValueOf(c).MapIndex(reflect.ValueOf("娜扎")).IsValid())}结果:var a *int IsNil: truenil IsValid: false不存在的结构体成员: false不存在的结构体方法: falsemap中不存在的键: falseProcess finished with exit code 0
4.结构体反射4.1与结构体相关的方法
任意值通过reflect.TypeOf()获得反射对象信息后,如果他的类型时结构体,可以通过反射值对象reflect.type的NumField()和Field()方法获得结构体成员的详细信息。reflect.Type中,与结构体成员相关的方法如下:
上面介绍的方法中,有的返回值类型中含有StructField类型StructField类型用来描述结构体中的字段信息。type StructField struct { // Name是字段的名字。PkgPath是非导出字段的包路径,对导出字段该字段为""。 // 参见http://golang.org/ref/spec#Uniqueness_of_identifiers Name string PkgPath string Type Type // 字段的类型 Tag StructTag // 字段的标签 Offset uintptr // 字段在结构体中的字节偏移量 Index []int // 用于Type.FieldByIndex时的索引切片 Anonymous bool // 是否匿名字段}
4.3结构体反射示例
当我们使用反射得到一个结构体数据之后,可以通过索引依次获取其字段信息,也可以通过字段名去获取指定的字段信息。
package mainimport ( "fmt" "reflect")type student struct { Name string `json:"name"` Score int `json:"score"`}func main() { stu1 := student{ Name: "lili", Score: 98, } t:=reflect.TypeOf(stu1) fmt.Println(t.Name(),t.Kind()) //使用for循环遍历结构体的所有字段信息 for i:=0;i<t.NumField();i++{ field := t.Field(i) fmt.Printf("name:%s index:%d type:%v json tag:%v\n", field.Name, field.Index, field.Type, field.Tag.Get("json")) } // 通过字段名获取指定结构体字段信息 if scoreField, ok := t.FieldByName("Score"); ok { fmt.Printf("name:%s index:%d type:%v json tag:%v\n", scoreField.Name, scoreField.Index, scoreField.Type, scoreField.Tag.Get("json")) }}结果:student structname:Name index:[0] type:string json tag:namename:Score index:[1] type:int json tag:scorename:Score index:[1] type:int json tag:scoreProcess finished with exit code 0
package mainimport ( "fmt" "reflect")type student struct { Name string `json:"name"` Score int `json:"score"`}// 给student添加两个方法 Study和Sleep(注意首字母大写)func (s student) Study() string { msg := "好好学习,天天向上。" fmt.Println(msg) return msg}func (s student) Sleep() string { msg := "好好睡觉,快快长大。" fmt.Println(msg) return msg}func printMethod(x interface{}) { t := reflect.TypeOf(x) v := reflect.ValueOf(x) fmt.Println(t.NumMethod()) for i := 0; i < v.NumMethod(); i++ { methodType := v.Method(i).Type() fmt.Printf("method name:%s\n", t.Method(i).Name) fmt.Printf("method type:%s\n", methodType) // 通过反射调用方法传递的参数必须是 []reflect.Value 类型 var args = []reflect.Value{} v.Method(i).Call(args) }}func main() { var stu1 student printMethod(stu1)}结果:2method name:Sleepmethod type:func() string好好睡觉,快快长大。method name:Studymethod type:func() string好好学习,天天向上。Process finished with exit code 0
反射是一个强大并富有表现力的工具,能让我们写出更灵活的代码。但是反射不应该被滥用,原因有以下三个。1.基于反射的代码是极其脆弱的,反射中的类型错误会在真正运行的时候才会引发panic,那很可能是在代码写完的很长时间之后。2.大量使用反射的代码通常难以理解。3.反射的性能低下,基于反射实现的代码通常比正常代码运行速度慢一到两个数量级。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。