Examples of simple reflection Kotlin

In Kotlin, we have two ways to achieve functional reflection. One is the reflection of the Java package java.lang.reflect call the following API, another is a direct call kotlin.reflect package following Kotlin's API.
Directly attached to the bar code

data class KotlinGirl(
var name:String?=null,
var age:String?=null)

First to a constructor
then the code, where the code reflecting only a few simple, almost remaining usage

fun main() {
    //java方式反射
    var girlClass = KotlinGirl::class.java
    val con= girlClass.getConstructor(String::class.java, String::class.java)
    var newGirl=con.newInstance("love", "18")
    print(newGirl)
    //kotlin方式反射
    var girl=KotlinGirl()
    val con1=girl::age
    con1.set("123")
    print(girl)

}

Here Insert Picture Description
The first created entity object using java reflection of a KotlinGirl
second with kotlin own reflection changes the value of the new entity in the age of the object,
compare, first java reflection much faster than kotlin, this official explanation is no time, and the second is very simple kotlin comfortable, but the constructor is not too comfortable, we can try for reflection methods and member variables with the

Finally, wanted to reflection and Groovy, and several of the scala write, too many pictures, write separate it

Published 71 original articles · won praise 276 · views 70000 +

Guess you like

Origin blog.csdn.net/weixin_43486804/article/details/104020222