博客
关于我
反射的快速入门
阅读量:666 次
发布时间:2019-03-16

本文共 1902 字,大约阅读时间需要 6 分钟。

一 需求

1 编写一个案例,演示对基本数据类型、interface{}、reflect.Value 进行反射的基本操作。

2 编写一个案例,演示对结构体类型、interface{}、reflect.Value 进行反射的基本操作。

二 代码

package mainimport (   "fmt"   "reflect")// 基本数据类型演示反射func reflectTest01(b interface{}) {   // 通过反射获取传入的变量的 type 和 kind 的值。   // 先获取到 reflect.Type   rTyp := reflect.TypeOf(b)   fmt.Println("rType=", rTyp)   // 获取到 reflect.Value   rVal := reflect.ValueOf(b)   n2 := 2 + rVal.Int()   // n3 := rVal.Float()   fmt.Println("n2=", n2)   // fmt.Println("n3=", n3)   fmt.Printf("rVal=%v rVal type=%T\n", rVal, rVal)   // 将 rVal 转成 interface{}   iV := rVal.Interface()   // 将 interface{} 通过断言转成需要的类型   num2 := iV.(int)   fmt.Println("num2=", num2)   // 获取变量对应的 Kind   rkind := rVal.Kind()   fmt.Println("kind=", rkind)}// 结构体演示反射func reflectTest02(b interface{}) {   // 通过反射获取传入的变量的 type 和 kind 的值。   // 先获取到 reflect.Type   rTyp := reflect.TypeOf(b)   fmt.Println("rType=", rTyp)   // 获取到 reflect.Value   rVal := reflect.ValueOf(b)   // 获取变量对应的 Kind   kind1 := rVal.Kind() // reflect.Value 的 Kind()   kind2 := rTyp.Kind() // reflect.Type 的 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}func main() {   // 先定义一个int   var num int = 100   reflectTest01(num)   fmt.Println("--------------------------------------------------------------------")   // 定义一个 Student 的实例   stu := Student{      Name: "tom",      Age:  20,   }   reflectTest02(stu)}

三 测试

rType= int

n2= 102

rVal=100 rVal type=reflect.Value

num2= 100

kind= int

--------------------------------------------------------------------

rType= main.Student

kind =struct kind=struct

iv={tom 20} iv type=main.Student

stu.Name=tom

转载地址:http://arxqz.baihongyu.com/

你可能感兴趣的文章
Netty工作笔记0050---Netty核心模块1
查看>>
Netty工作笔记0057---Netty群聊系统服务端
查看>>
Netty工作笔记0060---Tcp长连接和短连接_Http长连接和短连接_UDP长连接和短连接
查看>>
Netty工作笔记0063---WebSocket长连接开发2
查看>>
Netty工作笔记0068---Protobuf机制简述
查看>>
Netty工作笔记0070---Protobuf使用案例Codec使用
查看>>
Netty工作笔记0072---Protobuf内容小结
查看>>
Netty工作笔记0074---handler链调用机制实例1
查看>>
Netty工作笔记0077---handler链调用机制实例4
查看>>
Netty工作笔记0081---编解码器和处理器链梳理
查看>>
Netty工作笔记0083---通过自定义协议解决粘包拆包问题1
查看>>
Netty工作笔记0084---通过自定义协议解决粘包拆包问题2
查看>>
Netty工作笔记0085---TCP粘包拆包内容梳理
查看>>
Netty常用组件一
查看>>
Netty常见组件二
查看>>
netty底层——nio知识点 ByteBuffer+Channel+Selector
查看>>
netty底层源码探究:启动流程;EventLoop中的selector、线程、任务队列;监听处理accept、read事件流程;
查看>>
Netty心跳检测
查看>>
Netty心跳检测机制
查看>>
netty既做服务端又做客户端_网易新闻客户端广告怎么做
查看>>