Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 981 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to set delegated property value by reflection in kotlin?

#1
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?
Reply

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

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")
}

<sup>If the property is delegated, the call will be dispatched to the delegate.</sup>

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`.

[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through