反射Reflection
什么是反射?
反射就是在代码运行时,能检验程序代码本身的库
类引用Class Reference
就是将普通的类转换为KClass
使用::class
fun BaseMain() {
var c = Student::class
if (c is KClass) {
println("c is KClass!")
} else {
println("c is not KClass!")
}
}
class Student(name: String) {
var name = ""
}
/**打印
c is KClass!
*/
- Object 来获取
除了利用类直接获取外,还可以用类的对象获取KClass
var stu = Student("Nbin")
var c2 = stu::class
if (c2 is KClass) {
println("the object is KClass!")
} else {
println("The c2 is not KClass!")
}
/**
the object is KClass!
*/
方法引用Function Reference
有两种,一种普通调用,也可以直接用::function
fun BaseMain() {
println(getStringNumDes(100) {
checkZero(it)
})
println(getStringNumDes(-10, ::checkZero))
}
fun checkZero(num: Int): String {
if (num > 0) return "This is positive number." else return "This is negative number!"
}
fun getStringNumDes(num: Int, check: (Int) -> String): String {
var str = check(num)
return "This is judge: $str"
}
/**
This is judge: This is positive number.
This is judge: This is negative number!
*/
属性引用Property Reference
看看和对象直接点号的区别
fun BaseMain() {
var stu = Student()
stu.name = "Nbin"
println("This name type is '${stu::name}' and the name is ${stu::name.get()}")
stu::name.set("Black")
println("This name is changing to ${stu.name}")
}
class Student {
var name = ""
}
/**打印
This name type is 'var coin.otc.com.otc.kotlin.Student.name: kotlin.String' and the name is Nbin
This name is changing to Black
*/
方法作为变量
来看一波,属性,构造方法也可以使用:: 进行调用。
fun BaseMain() {
var pr = ::printG
pr(arrayOf("1", "1", "222222222222222222222222222222222222222222"))
}
fun printG(vararg les: String) {
var strs = StringBuffer()
for (le in les) {
strs.append(le)
strs.append(",")
}
println(strs.toString())
}
/**
1,1,222222222222222222222222222222222222222222,
*/