反射的基本介绍
基本介绍
- 反射可以在运行时动态获取变量的各种信息, 比如变量的类型(type),类别(kind)
- 如果是结构体变量,还可以获取到结构体本身的信息(包括结构体的字段、方法)
- 通过反射,可以修改变量的值,可以调用关联的方法。
-
反射的应用场景
不知道接口调用哪个函数,根据传入参数在运行时确定调用的具体接口,这种
需要对函数或方法反射。例如以下这种桥接模式
func bridge(funcPtr interface{}, args ...interface{})
第一个参数funcPtr以接口的形式传入函数指针,函数参数args以可变参数的形式传入,bridge函数中
可以用反射来动态执行funcPtr函数
- 对结构体序列化时,如果结构体有指定Tag,也会使用到反射生成对应的字符串。
``go package main import ( "fmt" "reflect" ) //定义了一个Monster结构体 type Monster struct { Name string
json:”name”Age int
json:”monster_age”Score float32
json:”成绩”` Sex string }
func main() { //创建了一个Monster实例 var a Monster = Monster{ Name: “黄鼠狼精”, Age: 400, Score: 30.8, } //将Monster实例反射生成对应的字符串 data, _ := json.Marshal(a) fmt.Printf(“json result: %v\n”, string(data)) //json result: {“name”:”黄鼠狼精”,”monster_age”:400,”成绩”:30.8,”Sex”:””} }
<a name="Si57i"></a>
## 反射重要的函数和概念
1. `reflect.TypeOf(变量名)`,获取变量的类型,返回`reflect.Type`类型
1. `reflect.ValueOf(变量名)`,获取变量的值,返回`reflect.Value`类型`reflect.Value` 是一个结构体类型。通过`reflect.Value`,可以获取关于该变量的很多信息。
1. 变量、`interface{} `和 `reflect.Value`是可以相互转换的,这点在实际开发中,会经常使用到。
![](https://cdn.nlark.com/yuque/0/2022/jpeg/2608713/1655877378732-24f87a4a-2dc1-4a0d-9536-b12456e50b4e.jpeg)
<a name="kt7Hd"></a>
# 反射的快速入门
> 演示对(基本数据类型、interface{}、reflect.Value)进行反射的基本操作
> 演示对(结构体类型、interface{}、reflect.Value)进行反射的基本操作
```go
package main
import (
"fmt"
"reflect"
)
//专门演示反射[对基本数据类型的反射]
func reflectTest01(b interface{}) {
//通过反射获取的传入的变量的 type , kind, 值
//1. 先获取到 reflect.Type
rTyp := reflect.TypeOf(b)
fmt.Println("rType=", rTyp)
//2. 获取到 reflect.Value
rVal := reflect.ValueOf(b)
fmt.Printf("rVal=%v rVal type=%T\n", rVal, rVal)
// 将 reflect.Value 转成需要的类型
n2 := rVal.Int()
fmt.Println("n2=", n2)
//下面我们将 rVal 转成 interface{}
iV := rVal.Interface()
//将 interface{} 通过断言转成需要的类型
num2 := iV.(int)
fmt.Println("num2=", num2)
}
//专门演示反射[对结构体的反射]
func reflectTest02(b interface{}) {
//通过反射获取的传入的变量的 type , kind, 值
//1. 先获取到 reflect.Type
rTyp := reflect.TypeOf(b)
fmt.Println("rType=", rTyp)
//2. 获取到 reflect.Value
rVal := reflect.ValueOf(b)
fmt.Printf("rVal: %v\n", rVal)
//3. 获取 变量对应的Kind
//(1) rVal.Kind() ==>
kind1 := rVal.Kind()
//(2) rTyp.Kind() ==>
kind2 := rTyp.Kind()
fmt.Printf("kind =%v kind=%v\n", kind1, kind2)
//下面我们将 rVal 转成 interface{}
iV := rVal.Interface()
fmt.Printf("iv=%v iv type=%T \n", iV, iV)
//将 interface{} 通过断言转成需要的类型
//这里,我们就简单使用了一带检测的类型断言.
//同学们可以使用 swtich 的断言形式来做的更加的灵活
stu, ok := iV.(Student)
if ok {
fmt.Printf("stu.Name=%v\n", stu.Name)
}
}
type Student struct {
Name string
Age int
}
type Monster struct {
Name string
Age int
}
func main() {
//请编写一个案例,
//演示对(基本数据类型、interface{}、reflect.Value)进行反射的基本操作
//1. 先定义一个int
var num int = 100
reflectTest01(num)
//2. 定义一个Student的实例
stu := Student{
Name: "tom",
Age: 20,
}
reflectTest02(stu)
}
rType= int
rVal=100 rVal type=reflect.Value
n2= 100
num2= 100
rType= main.Student
rVal: {tom 20}
kind =struct kind=struct
iv={tom 20} iv type=main.Student
stu.Name=tom
反射的注意事项和细节
reflect.Value.Kind,获取变量的类别,返回的是一个常量
type Kind uint //Kind代表Type类型值表示的具体分类。零值表示非法分类。 const ( Invalid Kind = iota Bool Int Int8 Int16 Int32 Int64 Uint Uint8 Uint16 Uint32 Uint64 Uintptr Float32 Float64 Complex64 Complex128 Array Chan Func Interface Map Ptr Slice String Struct UnsafePointer )
Type 和 Kind 的区别
Type 是类型, Kind 是类别, Type 和 Kind 可能是相同的,也可能是不同的.
比如:var num int = 10
num 的 Type 是 int , Kind 也是 int
比如:var stu Student
stu 的 Type 是 pkg1.Student , Kind 是 struct
- 通过反射可以在让变量在
interface{}
和Reflect.Value
之间相互转换 - 使用反射的方式来获取变量的值(并返回对应的类型),要求数据类型匹配,比如x是int,
那么就应该使用reflect.Value(x).lnt()
,而不能使用其它的,否则报panic
- 通过反射的来修改变量, 注意当使用 SetXxx 方法来设置需要通过对应的指针类型来完成, 这样才能改变传入
的变量的值, 同时需要使用到 reflect.Value.Elem()方法
package main
import (
"reflect"
"fmt"
)
//通过反射,修改,
// num int 的值
func reflectInt(b interface{}){
val := reflect.ValueOf(b)
fmt.Printf("val: %v val type: %T val kind: %v\n", val,val, val.Kind())
//Elem返回v持有的接口保管的值的Value封装,或者v持有的指针指向的值的Value封装
val.Elem().SetInt(20)
fmt.Printf("val: %v\n", val)
}
func main() {
var num int = 10
reflectInt(&num)
fmt.Println("num=", num) // 20
}
val: 0xc000016088 val type: reflect.Value val kind: ptr
val: 0xc000016088
num= 20
- reflect.Value.Elem() 应该如何理解?
num := 10 ptr *int = &num num2 := *ptr //类似 val.Elem()
反射最佳实践
看段代码,判断是否正确,为什么
package main
import (
"fmt"
"reflect"
)
func main() {
var str string = "tom" //ok
fs := reflect.ValueOf(str) //ok fs -> string
fs.SetString("jack") //error
fmt.Printf("%v\n", str)
}
package main
import (
"fmt"
"reflect"
)
func main() {
var str string = "tom" //ok
fs := reflect.ValueOf(&str) //ok fs -> string
fs.Elem().SetString("jack") //ok
fmt.Printf("%v\n", str) // jack
}
使用反射来遍历结构体的字段,调用结构体的方法,并获取结构体标签的值
package main
import (
"fmt"
"reflect"
)
//定义了一个Monster结构体
type Monster struct {
Name string `json:"name"`
Age int `json:"monster_age"`
Score float32 `json:"成绩"`
Sex string
}
//方法,返回两个数的和
func (s Monster) GetSum(n1, n2 int) int {
return n1 + n2
}
//方法, 接收四个值,给s赋值
func (s Monster) Set(name string, age int, score float32, sex string) {
s.Name = name
s.Age = age
s.Score = score
s.Sex = sex
}
//方法,显示s的值
func (s Monster) Print() {
fmt.Println("---start~----")
fmt.Println(s)
fmt.Println("---end~----")
}
func TestStruct(a interface{}) {
//获取reflect.Type 类型
typ := reflect.TypeOf(a)
//获取reflect.Value 类型
val := reflect.ValueOf(a)
//获取到a对应的类别
kd := val.Kind()
//如果传入的不是struct,就退出
if kd != reflect.Struct {
fmt.Println("expect struct")
return
}
//获取到该结构体有几个字段
num := val.NumField()
fmt.Printf("struct has %d fields\n", num) //4
//变量结构体的所有字段
for i := 0; i < num; i++ {
fmt.Printf("Field %d: 值为=%v\n", i, val.Field(i))
//获取到struct标签, 注意需要通过reflect.Type来获取tag标签的值
tagVal := typ.Field(i).Tag.Get("json")
//如果该字段于tag标签就显示,否则就不显示
if tagVal != "" {
fmt.Printf("Field %d: tag为=%v\n", i, tagVal)
}
}
//获取到该结构体有多少个方法
numOfMethod := val.NumMethod()
fmt.Printf("struct has %d methods\n", numOfMethod)
//var params []reflect.Value
//方法的排序默认是按照 函数名的排序(ASCII码)
val.Method(1).Call(nil) //获取到第二个方法。调用它
//调用结构体的第1个方法Method(0)
var params []reflect.Value //声明了 []reflect.Value
params = append(params, reflect.ValueOf(10))
params = append(params, reflect.ValueOf(40))
res := val.Method(0).Call(params) //传入的参数是 []reflect.Value, 返回[]reflect.Value
fmt.Println("res=", res[0].Int()) //返回结果, 返回的结果是 []reflect.Value*/
}
func main() {
//创建了一个Monster实例
var a Monster = Monster{
Name: "黄鼠狼精",
Age: 400,
Score: 30.8,
}
//将Monster实例传递给TestStruct函数
TestStruct(a)
}
struct has 4 fields
Field 0: 值为=黄鼠狼精
Field 0: tag为=name
Field 1: 值为=400
Field 1: tag为=monster_age
Field 2: 值为=30.8
Field 2: tag为=成绩
Field 3: 值为=
struct has 3 methods
---start~----
{黄鼠狼精 400 30.8 }
---end~----
res= 50