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

怎么做呢?

推荐答案

如果要将该属性设置为record.name = "...",则可以使用kotlin-reflect,这是Kotlin反射API(请参见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")
}

如果委托该属性,则调用将调度到委托.

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.

Kotlin相关问答推荐

如何在Kotlin中为两个数据类创建可重用的方法?

Kotlin—列出具有不同T的列表之间的操作'

Kotlin-删除按钮周围的空格

相当于roomdb中的DateTime Bigint列的是什么

Kotlin扩展函数未调用Hibernate/JPA中的重写函数

如何避免键盘打开时jetpack compose 内容上升

循环中的每个元素都应填充行中可用的所有可用空间

如何处理基于枚举提前返回的 forEach 循环,Kotlin 中的一条路径除外

parallelStream()和asSequence().asStream().parallel()之间的区别

为空数组添加值

Android Studio 4.0.0 Java 8 库在 D8 和 R8 构建错误中脱糖

作为 Kotlin 中的函数的结果,如何从 Firestore 数据库返回列表?

无法为 retrofit2.Call 调用无参数构造函数

Android Studio 将 Java 转换为 Kotlin 错误无法推断此参数的类型

Firestore - 如何在 Kotlin 中排除数据类对象的字段

将ExpectedException与Kotlin一起使用

如何获取Kotlin中变量的名称?

在 suspendCoroutine 块中调用挂起函数的适当方法是什么?

你如何在 Kotlin 中注释 Pair 参数?

为什么 Kotlin 会收到这样的 UndeclaredThrowableException 而不是 ParseException?