博客
关于我
反射的快速入门
阅读量: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底层源码探究:启动流程;EventLoop中的selector、线程、任务队列;监听处理accept、read事件流程;
查看>>
Netty心跳检测
查看>>
Netty心跳检测机制
查看>>
netty既做服务端又做客户端_网易新闻客户端广告怎么做
查看>>
netty时间轮
查看>>
Netty服务端option配置SO_REUSEADDR
查看>>
Netty核心模块组件
查看>>
Netty框架内的宝藏:ByteBuf
查看>>
Netty框架的服务端开发中创建EventLoopGroup对象时线程数量源码解析
查看>>
Netty源码—1.服务端启动流程一
查看>>
Netty源码—1.服务端启动流程二
查看>>
Netty源码—2.Reactor线程模型一
查看>>
Netty源码—2.Reactor线程模型二
查看>>
Netty源码—3.Reactor线程模型三
查看>>
Netty源码—3.Reactor线程模型四
查看>>
Netty源码—4.客户端接入流程一
查看>>
Netty源码—4.客户端接入流程二
查看>>
Netty源码—5.Pipeline和Handler一
查看>>
Netty源码—5.Pipeline和Handler二
查看>>
Netty源码—6.ByteBuf原理一
查看>>