当前位置:网站首页>Kotlin反射
Kotlin反射
2022-08-08 20:26:00 【不忘初衷z】
KOtlin-reflect 核心 API
主要常用接口:
KClass
提供了很多函数可以获得运行时对象对相关信息。
KClass的一个实例表示对类对引用,在程序代码中引用类使用::运算符
用法:
方式1
var clz1 = Int::class
方式2
var user = User::class
方法:
simpleName 获取类名
qualifiedName 类全名
isAbstract 是否抽象类
isData 是否数据类
constructors 获取所有构造函数
primaryConstructor 获取主构造函数
方法很多!
调用函数
通过反射调用函数需要KFunction实例,通过两种方式获取
一种是函数引用;另外一种是通过KClass提供对API获取
具体代码,首先创建一个类
class user{
var name
var age
fun setNameAndAge(name:String,age:Int){
this,name = name
this.age = age
}
fun add(a:Int,b:int) = a + b
fun sub(a:Int,b:int) = a - b
fun calculate(opr:Char):(Int,Int) - > Int = if (opr == “+”)::add else ::sub
}
fun main(){
var fn1 = ::add
var fn2 = ::sub 创建两个引用
val fun = calculate(“+”)
fn1(10,5) //15
fn2(10,5) // 5
fn3(10,5) //15
val clz = user::class 申明类的引用
val user = clz.createInstance() 获取反射性实例化对象
clz.functions.forEach { println(it.name)} 调用函数集合,打印当前类的方法集合
val user1 = clz.functions.first 获取类中的第一个函数
user1.call(user,“张三”,15) 调用第一个函数方法,传值需要调用call方法并且要把反射实例化对象传入第一个参数中
}
调用属性
KProperty 通过两种方式获取,一种属性引用,一种是通过KClass提供的API获取
memberProperties 获取所有属性成员
边栏推荐
- OpenEuler's Ways to Improve Resource Utilization 02: Effects under Typical Applications
- XTU OJ 1075 求最小公倍数
- 方舟建筑代码指令大全
- What are the latest developments in the handling of false information?KDD2022 "Fighting Misinformation and Responding to Media Bias" tutorial, 161 pages ppt
- fillder4 keeps prompting the system proxy was changed, watch me solve it
- 有幸与美团大佬共同探讨单节点连接数超1.5W的问题
- 实践篇2:深度学习之----LetNet之tensorflow2的实现
- iMeta | 深圳先进院戴磊组开发可同时提取共存菌株的组成和基因成分谱的菌株分析工具...
- Ansible自动化运维工具(一)安装及模块
- 1259 Alice and Bob
猜你喜欢
数据解读!智能座舱“升级战”背后,本土供应链加速崛起
Maykel Studio OpenHarmony Device Development Training Notes - Chapter 6 Study Notes
openEuler 资源利用率提升之道02:典型应用下的效果
Intel两大FPGA产品部署中国:性能升45%、功耗降40%
Yarn 总结(未完待续)
瑞吉外卖项目实战Day06--手机端
Canvans:绘制饼图和玫瑰饼图
What are the latest developments in the handling of false information?KDD2022 "Fighting Misinformation and Responding to Media Bias" tutorial, 161 pages ppt
How can recommender systems be trusted?A review of the latest "Trusted Recommender System" from Rutgers University, a 43-page pdf explaining the composition and technology of trusted RS
文档管理系统对于企业来说有哪些作用?
随机推荐
fillder4 keeps prompting the system proxy was changed, watch me solve it
Gartner:2022年全球半导体收入增长预计将放缓至7%,远低于2021年26.3%
接口测试经典面试题:Session、cookie、token有什么区别?
黑猫带你学Makefile第6篇:Makefile重要规则
五大理由告诉你为什么开发人员选择代码质量静态分析工具Klocwork来实现软件安全
XTU OJ 1075 求最小公倍数
制作实例分割数据集
给大龄准备转行网络工程师的朋友一些建议
OneNote 教程,如何在 OneNote 中检查拼写?
Experience Sharing | A low-cost and fast-paced approach to building an enterprise knowledge management system
经验分享|低成本快节奏搭建企业知识管理系统的方法
学习与尝试 --> 事件风暴
PyTorch入门(六):模型的训练套路
文档管理系统对于企业来说有哪些作用?
Mei cole studio OpenHarmony equipment development training notes - the first learn notes
场外基金开户在手机办理安全吗?
学习笔记:2.3 静态链表 循环链表 双向链表
流媒体后视镜前装搭载小幅下滑,远峰与镜泰排位争夺白热化
利用shell脚本同时编译生成多个cmake工程
LitJson使用中的一些问题