博客
关于我
反射的快速入门
阅读量: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/

你可能感兴趣的文章
Mysql 数据库InnoDB存储引擎中主要组件的刷新清理条件:脏页、RedoLog重做日志、Insert Buffer或ChangeBuffer、Undo Log
查看>>
mysql 数据库备份及ibdata1的瘦身
查看>>
MySQL 数据库备份种类以及常用备份工具汇总
查看>>
mysql 数据库存储引擎怎么选择?快来看看性能测试吧
查看>>
MySQL 数据库操作指南:学习如何使用 Python 进行增删改查操作
查看>>
MySQL 数据库的高可用性分析
查看>>
MySQL 数据库设计总结
查看>>
Mysql 数据库重置ID排序
查看>>
Mysql 数据类型一日期
查看>>
MySQL 数据类型和属性
查看>>
mysql 敲错命令 想取消怎么办?
查看>>
Mysql 整形列的字节与存储范围
查看>>
mysql 断电数据损坏,无法启动
查看>>
MySQL 日期时间类型的选择
查看>>
Mysql 时间操作(当天,昨天,7天,30天,半年,全年,季度)
查看>>
MySQL 是如何加锁的?
查看>>
MySQL 是怎样运行的 - InnoDB数据页结构
查看>>
mysql 更新子表_mysql 在update中实现子查询的方式
查看>>
MySQL 有什么优点?
查看>>
mysql 权限整理记录
查看>>