Creating a new instance of a KClass
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
}
You can use the Java class to create new instance:
MyClass::class.java.newInstance()