码迷,mamicode.com
首页 > 编程语言 > 详细

go语言系列-反射

时间:2020-04-06 21:03:22      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:包括   检测   技术   细节   asc   return   import   不能   imp   

反射

  1. 反射可以在运行时动态获取变量的各种信息,比如变量的类型(type),类别(kind)

  2. 如果是结构体变量,还可以获取到结构体本身的信息(包括结构体的字段、方法)

  3. 通过反射,可以修改变量的值,可以调用关联的方法

  4. 使用反射,需要import(“reflect”)
    技术图片

引出反射

import (
   "encoding/json"
   "fmt"
)
type Monster struct {
   Name string `json:"monsterName"`
   Age int `json:"monsterAge"`
   Sal float64 `json:"monsterSal"`
   Sex string `json:"monsterSex"`
}
func main()  {
   m := Monster{
      Name : "玉兔精",
      Age : 20,
      Sal : 888.99,
      Sex : "female",
   }
   data,_ := json.Marshal(m)
   fmt.Println("json result:", string(data))
}

输出结果:json result: {"monsterName":"玉兔精","monsterAge":20,"monsterSal":888.99,"monsterSex":"female"}思考问题:为什么

思考问题

为什么序列化后,key - val的key值是结构体Tag的值,而不是字段的名称,比如:不是Name 而是:"monsterName":"玉兔精"

引出反射

使用反射机制,编写函数的适配器,桥连接

技术图片

反射的应用场景

反射常见应用场景有以下两种

  1. 不知道接口调用哪个函数,根据传入参数在运行时确定调用的具体接口,这种需要对函数或方法反射。例如以下这种桥接模式,比如前面提出的问题
func bridge(funcPtr interface{}, args ...interface{})

第一个参数funcPtr以接口的形式传入函数指针,函数参数args以可变参数的形式传入,bridge函数中可以用反射来动态执行funcPtr函数

  1. 对结构体序列化时,如果结构体有指定Tag,也会使用到反射生成对应的字符串
type Monster struct {
   Name string `json:"monsterName"`
   Age int `json:"monsterAge"`
   Sal float64 `json:"monsterSal"`
   Sex string `json:"monsterSex"`
}

反射重要的函数和概念

  1. reflect.TypeOf(变量名),获取变量的类型,返回reflect.Type类型

  2. reflect.ValueOf(变量名),获取变量的值,返回reflect.Value类型reflect.Value是一个结构体类型。通过reflect.Value,可以获取到关于该变量的很多信息
    技术图片
    3)变量、interface{} 和 reflect.Value是可以相互转换的,这点在实际开发中,会经常使用到。画出示意图
    技术图片
    技术图片

反射的快速入门

编写一个案例,演示对(结构体、基本数据类型、interface{}、reflect.Value)进行反射的基本操作,代码演示

import (
   "fmt"
   "reflect"
)
//专门演示反射
func reflectTest01(b interface{}) {
   //通过反射获取的传入的变量的type,kind,值
   //1. 先获取到reflect.Type
   rTyp := reflect.TypeOf(b)
   fmt.Println("rTyp = ", rTyp)
   //2. 获取到reflect.Vakue
   rVal := reflect.ValueOf(b)
   n2 := 2 + rVal.Int()
   fmt.Println("n2 = ", n2)
   fmt.Printf("rVal = %v rVal type = %T\n", rVal, rVal)
   //下面将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("rTyp = ", rTyp)
   //2. 获取到reflect.Value
   rVal := reflect.ValueOf(b)

   //下面将rVal转成interface{}
   iV := rVal.Interface()
   fmt.Printf("iv = %v iv type = %T\n", iV, iV)
   //将interface{}通过断言转成需要的类型
   //这里,简单使用到检测的类型断言
   //也可以使用switch的断言形式来做的更加的灵活
   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)
}
//rTyp =  int
//n2 =  102
//rVal = 100 rVal type = reflect.Value
//num2 =  100
//rTyp =  main.Student
//iv = {tom 20} iv type = main.Student
//stu.Name = tom

反射的注意事项和细节

1)reflect.Value.Kind 获取变量的类别,返回的是一个常量
技术图片
2) Type和Kind的区别

? Type是类型,Kind是类别,Type和Kind可能是相同的,也可能是不同的

? 比如:var num int = 10 num的Type是int,Kind也是int

? 比如:var stu Student stu的Type是pKg1.Student,Kind是struct

  1. 通过反射可以让变量在interface{}和Reflect.Value之间相互转换,这点在前面画过示意图并在快速入门案例中讲解过,这里看下如何在代码中体现
    技术图片
  2. 使用反射的方式来获取变量的值(并返回对应的类型),要求数据类型匹配,比如x是int,那么就应该使用reflect.Value(x).Int(),而不能使用其它的,否则报panic
    技术图片
  3. 通过反射来修改变量,注意当使用SetXxx方法来设置需要通过对应的指针类型来完成,这样才能改变传入的变量的值,同时需要使用到reflect.Value.Elem()方法
import (
   "fmt"
   "reflect"
)

func testInt(b interface{})  {
   val := reflect.ValueOf(b)
   fmt.Printf("val type = %T\n", val)
   val.Elem().SetInt(110)
   fmt.Printf("val = %v\n", val)
}
func main()  {
   var num int = 20
   testInt(&num)
   fmt.Println("num = ", num)
}
//val type = reflect.Value
//val = 0xc000054080
//num =  110
  1. reflect.Valut.Elem()应该如何理解
    技术图片

反射练习

  1. 给一个变量 var v float64 = 1.2 ,请使用反射来得到它的reflect.Value,然后获取对应的Type,Kind和值,并将reflect.Value转换成interface{},再将interface{}转换成float64

  2. 看段代码,判断是否正确,为什么

import (
   "fmt"
   "reflect"
)

func main()  {
   var str string = "tom" // ok
   fs := reflect.ValueOf(&str) // ok fs -> string
   //fs.SetString("jack")  //error
   fs.Elem().SetString("jack")
   fmt.Printf("%v\n", str)
}
//jack

反射最佳实践

  1. 使用反射来遍历结构体的字段,调用结构体的方法,并获取结构体标签的值
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
  1. 使用反射的方式来获取结构体的tag标签,遍历字段的值,修改字段值,调用结构体方法(要求:通过传递地址的方式完成,在前面案例上修改即可)

  2. 定义了两个函数test1和test2,定义一个适配器函数用作统一处理接口

  3. 使用反射操作任意结构体类型

  4. 使用反射创建并操作结构体

  5. 编写一个Cal结构体,有两个字段Num1和Num2

  6. 方法GetSub(name string)

  7. 使用反射遍历Cal结构体所有的字段信息

  8. 使用反射机制完成对GetSub的调用,输出形式为”tom 完成了减法运算,8 - 3 = 5”

go语言系列-反射

标签:包括   检测   技术   细节   asc   return   import   不能   imp   

原文地址:https://www.cnblogs.com/zisefeizhu/p/12643858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!