简体   繁体   中英

Why we write NextActivity::class.java although this is a kotlin class?

We have to write this line with the extension .java although its extension is .kt I think Kotlin file converts into the java file but the java also converts in byte code so we can also use .class file If the Kotlin code converts into the java code.

NextActivity::class.java to NextActivity::class.kt //not worked

btn?.setOnClickListener {
   startActivity(Intent(this, NextActivity::class.java))
}

So the question is why we write the .java in NextActivity::class.java

Question arises from here .

Because you want to access the methods of the Java Class .

I think they are not reimplemented from scratch in Kotlin so, in order to access them, you have to "reflect" your kotlin class to a Java one.

NextActivity::class returns the KClass reference and the KClass has the property java and the Intent contructor signature is Intent(Context packageContext, Class cls) so the second parameter is Class type So the final answer would be this is not the extension this is just property.

You are calling Java code from Kotlin. Intent is Java class in Android.

Doc: https://kotlinlang.org/docs/reference/reflection.html#class-references

Note that a Kotlin class reference is not the same as a Java class reference. To obtain a Java class reference, use the .java property on a KClass instance.

You cannot pass Kotlin class reference to Java (Intent in your case) and so you have to pass Java class reference.

From the interop doc: https://kotlinlang.org/docs/reference/java-interop.html#java-reflection

Java reflection works on Kotlin classes and vice versa. As mentioned above, you can use instance::class.java, ClassName::class.java or instance.javaClass to enter Java reflection through java.lang.Class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM