基本介绍

  • 反射可以在运行时动态的获取变量的各种信息,比如变量的类型(type)、类别(kind)
  • 如果是结构体变量,还可以获取到结构体本身的信息,包括结构体的字段、方法
  • 通过反射,可以修改变量的值,可以调用关联的方法
  • 使用反射,需要import(”reflect”)

反射

image.png

  1. 变量、interface{}、reflect.Value是可以相互转换的,这点在实际开发中,会经常使用到。

    image.png

    细节说明

    image.png
    image.png

代码案例

  1. package AdvancedLearn
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. type Student struct{
  7. Name string
  8. Age int
  9. }
  10. // 专门演示反射
  11. func reflectDemoInt(b interface{}){
  12. // 通过反射 获取传入变量的 type , kind , value
  13. rTyp := reflect.TypeOf(b)
  14. fmt.Println(rTyp)
  15. rVal := reflect.ValueOf(b) //不能直接参与计算
  16. fmt.Println(2+rVal.Int()) //转值计算
  17. fmt.Println(rVal)
  18. //将rVal转成 interface{} => 再转化为对应类型
  19. iV := rVal.Interface()
  20. num2 := iV.(int)
  21. fmt.Println(num2)
  22. }
  23. func reflectDemoStruct(b interface{}){
  24. // 通过反射 获取传入变量的 type , kind , value
  25. rTyp := reflect.TypeOf(b)
  26. fmt.Println("rType =",rTyp) // rType = AdvancedLearn.Student
  27. rVal := reflect.ValueOf(b) //不能直接参与计算
  28. fmt.Println("rValue =",rVal) // rValue = {BigHead 25}
  29. //将rVal转成 interface{} => 再转化为对应类型
  30. iV := rVal.Interface()
  31. fmt.Println(iV)
  32. // iV.Name 此时不可行
  33. stu2 , ok := iV.(Student)
  34. if ok{
  35. fmt.Println(stu2.Name,stu2.Age)
  36. }
  37. }
  38. func TestReflect() {
  39. // 基本数据类型 num的反射操作
  40. //var num int = 100
  41. //reflectDemoInt(num)
  42. // type = int(打印值,实际为reflect.type)
  43. // value = 100(打印值,实际为reflect.value)
  44. stu := Student{"BigHead",25}
  45. reflectDemoStruct(stu)
  46. }