反射
基本介绍
- 反射可以在运行时动态获取变量的各种信息,比如变量的类型(type),类别(kind)
- 如果是结构体变量,还可以获取到结构体本身的信息(包括结构体的字段、方法)
- 通过反射,可以修改变量的值,可以调用关联的方法。
- 使用反射,需要import (“reflect”)
![image-20220207150509551](https://gitee.com/jtyyds/drawing-bed/raw/master/phones9/image-20220207150509551.png)
![image-20220207150711130](https://gitee.com/jtyyds/drawing-bed/raw/master/phones9/image-20220207150711130.png)
![image-20220207151449782](https://gitee.com/jtyyds/drawing-bed/raw/master/phones9/image-20220207151449782.png)
![image-20220207151325830](https://gitee.com/jtyyds/drawing-bed/raw/master/phones9/image-20220207151325830.png)
反射快速入门
1.请编写一个案例,演示对(基本数据类型、interface{} reflect.Value)进行反射的基本操作
package main
import (
"fmt"
"reflect"
)
//请编写一个案例,演示对(基本数据类型、interface{}、reflect.Value)进行反射的基本操作
//专门演示反射
func reflectTest01(b interface{}) {
//通过反射获取传入的变量的type , kind , 值
//1. 先获取到 reflect.Type
rTyp := reflect.TypeOf(b)
fmt.Println("rTyp =", rTyp)
//2.获取到 reflect.Value
rVal := reflect.ValueOf(b)
n2 := 2 + rVal.Int()
fmt.Println("n2 =", n2)
fmt.Printf("rVal =%v type = %T \n", rVal, rVal)
//下面我们将 rVal 转成 interface{}
iV := rVal.Interface()
//将 interface{} 通过断言转成需要的类型
num2 := iV.(int)
fmt.Println("num2=", num2)
}
func main() {
//1.定义一个int
var num int = 100
reflectTest01(num)
}
2.请编写一个案例,演示对(结构体类型、interface、reflect.Value)进行反射的基本操作。
//专门演示对结构体的反射
func reflectTest02(b interface{}) {
//通过反射获取传入的变量的type , kind , 值
//1. 先获取到 reflect.Type
rTyp := reflect.TypeOf(b)
fmt.Println("rTyp =", rTyp)
//2.获取到 reflect.Value
rVal := reflect.ValueOf(b)
//3. 获取 kind
//1)rVal.Kind()
//2)rTyp.Kind()
kind1 := rVal.Kind()
kind2 := rTyp.Kind()
fmt.Printf("kind1=%v kind2=%v \n", kind1, kind2)
//下面我们将 rVal 转成 interface{}
iV := rVal.Interface()
fmt.Printf("iV = %v iV type = %T\n", iV, iV)
//将 interface{} 通过断言转成需要的类型
stu, ok := iV.(Student)
if ok {
fmt.Println("stu.Name", stu.Name)
}
}
type Student struct {
Name string
Age int
}
func main() {
//定义一个student的实例
stu := Student{
Name: "tome",
Age: 20,
}
reflectTest02(stu)
}
注意事项和细节
- reflect.Value.Kind,获取变量的类别,返回的是一个常量
- Type是类型,Kind是类别, Type和 Kind可能是相同的,也可能是不同的.比如: var num int = 10 num的Type是int , Kind也是int。比如: var stu Student stu的Type是包名.Student , Kind是struct
- 通过反射可以在让变量在interface和Reflect.Value之间相互转换。
- 使用反射的方式来获取变量的值(并返回对应的类型),要求数据类型匹配,比如x是int,那么就应该使用reflect.Value(x).Int(),而不能使用其它的,否则报panic
- 通过反射的来修改变量,注意当使用Setxxx方法来设置需要通过对应的指针类型来完成,这样才能改变传入的变量的值,同时需要使用到reflect.Value.Elem()方法
package main
import (
"fmt"
"reflect"
)
//通过反射,修改 num int 值
func reflect01(b interface{}) {
rVal := reflect.ValueOf(b)
//rVal 的kind 是
fmt.Printf("rVal kind = %v \n", rVal.Kind())
rVal.Elem().SetInt(20)
}
func main() {
var num int = 10
reflect01(&num)
fmt.Println("num=", num)
}
常量
- 常量使用const修改
- 常量在定义的时候,必须初始化常量不能修改
- 常量只能修饰bool、数值类型(int,float系列)、string类型
- 语法:const identifier [type] = value
![image-20220207160035153](https://gitee.com/jtyyds/drawing-bed/raw/master/phones9/image-20220207160035153.png)
package main
import "fmt"
func main() {
const (
a = iota
b
c
d
)
fmt.Println(a, b, c, d) // 0 1 2 3
}
package main
import "fmt"
func main() {
const (
a = iota
b = iota
c, d = iota, iota
)
fmt.Println(a, b, c, d) // 0 1 2 2
}
Golang 中没有常量名必须字母大写的规范比如TAX_RATE
仍然通过首字母的大小写来控制常量的访问范围
反射实践
1.使用反射来遍历结构体的字段,调用结构体的方法,并获取结构体标签的值
package main
import (
"fmt"
"reflect"
)
//定义了一个Monster结构体
type Monster struct {
Name string `json:"name"`
Age int `json:"monster_age"`
Score float32
Sex string
}
func (s Monster) Print() {
fmt.Println("---start----")
fmt.Println(s)
fmt.Println("----end----")
}
func (s Monster) GetSum(n1, n2 int) int {
return n1 + n2
}
func (s Monster) Set(name string, age int, score float32, sex string) {
s.Name = name
s.Age = age
s.Score = score
s.Sex = sex
}
func TestStruct(a interface{}) {
typ := reflect.TypeOf(a)
val := reflect.ValueOf(a)
kd := val.Kind()
if kd != reflect.Struct {
fmt.Println("expect struct")
return
}
num := val.NumField()
fmt.Printf("struct has %d fileds \n", num)
for i := 0; i < num; i++ {
fmt.Printf("Filed %d : 值为= %v", i, val.Field(i))
//获取到struct标签,只有需要通过reflect。Type来获取tag标签的值
tagVal := typ.Field(i).Tag.Get("json")
if tagVal != "" {
fmt.Printf("Field %d: tag为=%v \n", i, tagVal)
}
}
numOfMethod := val.NumField()
fmt.Printf("struct has %d methods \n", numOfMethod)
//var params []reflect.Value
//方法的排序默认是按照函数名的排序(ASCII码)
val.Method(1).Call(nil)
//调用结构体的第一个方法Method(0)
var params []reflect.Value
params = append(params, reflect.ValueOf(10))
params = append(params, reflect.ValueOf(40))
res := val.Method(0).Call(params)
fmt.Println("res = ", res[0].Int())
}
func main() {
var a Monster = Monster{
Name: "黄鼠",
Age: 400,
Score: 11.0,
}
TestStruct(a)
}