Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new instance of a KClass

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.

like image 764
Rich Avatar asked Nov 18 '16 08:11

Rich


People also ask

How do I create a new instance of a class in Kotlin?

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).

What is KClass in Kotlin?

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.

Is called when you create an instance of a class?

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.


2 Answers

You can use the Java class to create new instance:

MyClass::class.java.newInstance() 
like image 101
Ingo Kegel Avatar answered Sep 20 '22 21:09

Ingo Kegel


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 } 
like image 29
hotkey Avatar answered Sep 22 '22 21:09

hotkey