Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set delegated property value by reflection in kotlin?

My entity class:

class User : ActiveRecord<User>() {
    var name by Column(String.javaClass);
    var id by Column(Int.javaClass);
}

now I want to set name value by refelection:

var clazz = User().javaClass
var record = clazz.newInstance()
var field = record.getDeclaredField(it + "$" + "delegate")

field.set(record, "aa")

then error:

entity.Column field ActiveRecord4k.User.name$delegate to java.lang.String

how to do this?

like image 370
junk Avatar asked Jun 01 '17 10:06

junk


1 Answers

If you want to reflectively set the property as if it was record.name = "...", then you can use kotlin-reflect, the Kotlin reflection API (see the reference).

With kotlin-reflect, setting a property value is done like this:

val property = outputs::class.memberProperties.find { it.name == "name" }
if (property is KMutableProperty<*>) {
    property.setter.call(record, "value")
}

If the property is delegated, the call will be dispatched to the delegate.

Or, you can do that with Java reflection, finding the setter for your property first:

var setter = clazz.getDeclaredMethod("set" + it.capitalize())
setter.invoke(record, "aa")

But there is no way, at least at this point, to overwrite the delegate instance of that property, because the field storing it, name$delegate, is final.

like image 66
hotkey Avatar answered Sep 21 '22 01:09

hotkey