Creating A New Instance Of A KClass


Answer :

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
}


For those checking this question now, since Kotlin 1.1 there's also createInstance() extension method on KClass



Much like the accepted answer, this function works only in case class has an empty constructor or constructor with all default arguments.



https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect.full/create-instance.html



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable