I have a Kotlin class whose primary (and only) constructor is empty.
I have a reference to this class:
val kClass: KClass<MyClass> = MyClass::class
How do I create an instance of this class using reflection?
In Java I would do myClass.newInstance()
but it seems in Kotlin I need to find the constructor first:
kClass.constructors.first().call()
I have seen mention of primaryConstructor
in some bug reports but it's not showing up in my IDE.
Similar to using the fun keyword in Kotlin to create a new function, use the class keyword to create a new class. You can choose any name for a class , but it is helpful if the name indicates what the class represents. By convention, the class name is written in Upper Camel Case (also called Pascal Casing).
The KClass type is Kotlin's counterpart to Java's java. lang. Class type. It's used to hold references to Kotlin classes; you'll see what it lets you do with those classes in the “Reflection” section later in this chapter. The type parameter of KClass specifies which Kotlin classes can be referred to by this reference.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor.
You can use the Java class to create new instance:
MyClass::class.java.newInstance()
In your case, Java reflection might be enough: you can use MyClass::class.java
and create a new instance in the same way as you would with Java reflection (see @IngoKegel's answer).
But in case there's more than one constructor and you really need to get the primary one (not the default no-arg one), use the primaryConstructor
extension function of a KClass<T>
. It is a part of Kotlin reflection, which is not shipped within kotlin-stdlib
.
To use it, you have to add kotlin-reflect
as a dependency, e.g. a in Gradle project:
dependencies { compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" }
Assuming that there is ext.kotlin_version
, otherwise replace $kotlin_version
with the version you use.
Then you will be able to use primaryConstructor
, for example:
fun <T : Any> construct(kClass: KClass<T>): T? { val ctor = kClass.primaryConstructor return if (ctor != null && ctor.parameters.isEmpty()) ctor.call() else null }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With