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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With