dimanche 12 mars 2017

What is a proper way to create class instance from KType

I have two classes which might look like this

class MyClass {
    var myProperty: AnotherClass?
}

class AnotherClass {

}

Through reflection I iterate the properties of MyClass and when I find a KMutableProperty<*> which is null I want to create an instance of that class. Right now I'm doing something like this

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

but this seems like a terrible hack that needs to know internals and use Java magic instead of being pure Kotlin, is there a proper way to do what I want? Or is this the proper way?





Aucun commentaire:

Enregistrer un commentaire