Kotlin: Equivalent of getClass() for KClass
In Java we can resolve a variable's class through getClass()
like something.getClass()
. In Kotlin I am aware of something.javaClass
which is nice but I want to be able to get the KClass
in a similar way. I've seen the Something::class
syntax but this is not what I need. I need to get the KClass of a variable. Does such functionality exist?
Solution 1:
The easiest way to achieve this since Kotlin 1.1 is the class reference syntax:
something::class
If you use Kotlin 1.0, you can convert the obtained Java class to a KClass instance by calling the .kotlin
extension property:
something.javaClass.kotlin
Solution 2:
EDIT: See comments, below, and answer from Alexander, above. This advice was originally for Kotlin 1.0 and it seems is now obsolete.
Since the language doesn't support a direct way to get this yet, consider defining an extension method for now.
fun<T: Any> T.getClass(): KClass<T> {
return javaClass.kotlin
}
val test = 0
println("Kotlin type: ${test.getClass()}")
Or, if you prefer a property:
val<T: Any> T.kClass: KClass<T>
get() = javaClass.kotlin
val test = 0
println("Kotlin type: ${test.kClass}")
Solution 3:
Here's my solution
val TAG = javaClass.simpleName
With javaClass.simpleName you can obtain your class name. Also the above example is very useful for android developers to declare on top of the class as an instance variable for logging purposes.
Solution 4:
Here are different Implementations to get class names. You can utilize it as per your requirements.
import kotlin.reflect.KClass
val <T : Any > T.kClassName: KClass<out T>
get() {
return javaClass.kotlin
}
Here we can get the class name in kotlin
val <T : Any > T.classNameKotlin: String?
get() {
return javaClass.kotlin.simpleName
}
Here we can get the class name in kotlin
val <T : Any > T.classNameJava: String
get() {
return javaClass.simpleName
}
Here are the outputs to the following operations.
fun main(){
val userAge = 0
println(userAge.kClassName)
Output: class java.lang.Integer (Kotlin reflection is not available)
println(userAge.classNameKotlin)
Output: Int
println(userAge.classNameJava)
Output: Integer
}
Solution 5:
In Kotlin:
val className = serviceClass.javaClass.name