简体   繁体   中英

What is the difference between ::class and ::class.java in Kotlin?

In Java, we write .class (for example: String.class ) to get information about the given class. In Kotlin you can write ::class or ::class.java . What is the difference between them?

By using ::class , you get an instance of KClass. It is Kotlin Reflection API, that can handle Kotlin features like properties, data classes, etc.

By using ::class.java , you get an instance of Class. It is Java Reflection API, that interops with any Java reflection code, but can't work with some Kotlin features.

According to the Kotlin documentation, when we create an object using any class type as below the reference type will be type of KClass.

val c = MyClass::class  // reference type of KClass

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

val c = MyClass::class.java  // reference type of Java

You can refer the Kotlin documentation For further details. https://kotlinlang.org/docs/reference/reflection.html#class-references

First you need to understand about Reflection . According to the docs:

Reflection is a set of language and library features that allows for introspecting the structure of your own program at runtime.

In simple words, it gives you the ability to get the code you have written ie, the class name you have defined, the function name you have defined, etc. Everything you have written, you can access all these at runtime using Reflection .

::class and ::class.java are basic features of Reflection.

::class gives you a KClass<T> reference and ::class.java gives you Class<T> reference. Example,

val a = MyClass::class

can be interpreted as

val a = KClass<MyClass>()

Note: Above code is not syntactically correct, because KClass is an interface and interfaces cannot be instantiated. It is just to give you an idea.

A Class<T> class gives you information about the metadata of the T class like interfaces it is implementing, its functions' names, its package name, etc.

KClass is similar to Class but it gives information about some more properties(Kotlin related properties) than Class . All the information a KClass<T> reference can give you about the T class are listed here https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-class/#properties

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