Why we write NextActivity::class.java although thi

2020-02-06 07:41发布

问题:

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.

回答1:

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.



回答2:

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.