Open In App

How to Get the Class in Kotlin?

Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a “better language” than Java, but still be fully interoperable with Java code. In this article, we will discuss how to get the class reference in Kotlin. Primarily, we will be working with reflection. So let’s see what is 

Reflection:



Example

Here are different Implementations to get class names.




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 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
}

Java’s equivalent of resolving a variable’s name is with the .getClass () method, for example, something.getClass(). In Kotlin, we can achieve the same thing with something.javaClass. To get a reference to the reflection class, we used to do something.class in Java, whose Kotlin equivalent is something::class. This returns a KClass. The special feature of this KClass is that it provides introspection capabilities quite similar to the abilities provided to Java’s reflection class. Note that the KClass is different from Java’s Class object. If you want to obtain a Java Class object from Kotlin’s KClass, use the .java extension property:

val somethingkClass: KClass<Something> = Something: :class
val a: Class< Something> = somethingkClass. java
val b: Class < Something> = Something: : class . java

The latter example will be optimized by the compiler to not allocate an intermediate KClass instance. If you use Kotlin 1.0, you can convert the obtained Java class to a KClass instance by calling the .kotlin extension property, for example:

something.javaClass.kotlin.

As was just described, KClass provides you with introspection capabilities. Here are a few methods of KClass:


Article Tags :