当前位置:网站首页>Kotlin reflection -- Notes

Kotlin reflection -- Notes

2022-06-25 06:14:00 NO Exception?

1. Class reference

kotlin Is based on java1.6 Design , Fully compatible with java, So and java Many functions are interconnected . Such as java In reflection Class object , stay Kotlin It's called KClass object .

1.1 Class and KClass

Class

// stay kotlin In order to get Class object 

class ReflectDemo(val x: Int = 0) {
    

    constructor() : this(0) {
    
    }

    fun test() {
    
        println(x)
    }
}



// obtain Class Two methods of object instances 
val class1 = ReflectDemo().javaClass

val class2: Class<ReflectDemo> = ReflectDemo::class.java

KClass

//     obtain KClass Object instance method 
val kClass1 = ReflectDemo::class
val kClass2 = ReflectDemo().javaClass.kotlin

1.2 Get instance object


val instance = class1.newInstance()
instance.x
instance.test()

val instance2 = class2.newInstance()
instance2.x
instance2.test()

//kotlin Get instance object 
kClass1.objectInstance

1.3 Access method

// Get all methods containing parent classes 
kclass.memberFunctions
// Get all the methods of the current class 
kclass.declaredMemberFunctions

for (item in kclass.declaredMemberFunctions) {
    

    println("${
      item.name}")
    // Calling method 
    // item.call(reflectDemo)
} 

1.4 get attribute

val reflectDemo = ReflectDemo(33)

val kclass = ReflectDemo::class


//kclass.members  All properties of the current class and parent class 
//kclass.memberProperties Print all properties of the current class 
for (item in kclass.memberProperties) {
    
    val obj = item as KProperty<*>
    println("${
      obj.name}:${
      obj.call(reflectDemo)}")
}

1.5 Get comments

2. other

1.kotlin Object to map

fun <A : Any> toMap(a: A): Map<String, Any?> {
    
    // Traverse a All attributes of ,name to value
    return a::class.members.map {
     m ->
        val p = m as KProperty
        p.name to p.call(a)
    }.toMap()
}
原网站

版权声明
本文为[NO Exception?]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202201240537375.html