从 KType 创建类实例的正确方法是什么

Rit*_*ave 6 reflection jvm kotlin

我有两个可能看起来像这样的课程

class MyClass {
    var myProperty: AnotherClass?
}

class AnotherClass {

}
Run Code Online (Sandbox Code Playgroud)

通过反射,我迭代了 MyClass 的属性,当我发现 aKMutableProperty<*>为空时,我想创建该类的一个实例。现在我正在做这样的事情

val instance = MyClass()
val property = MyClass::myProperty
var subInstance = it.getter.call(instance)
if (subInstance == null) {
    it.setter.call(instance, property.returnType.jvmErasure.createInstance())
}
Run Code Online (Sandbox Code Playgroud)

但这似乎是一个可怕的黑客,需要了解内部结构并使用 Java 魔法而不是纯粹的 Kotlin,有没有合适的方法来做我想做的事?或者这是正确的方法?

yol*_*ole 5

你可以(property.returnType.classifier as KClass).createInstance()改用。