当我有一个带有伴生对象的类时,是否可以使用反射在这个伴生对象中设置属性?我可以在普通属性上做到这一点,但在伴生对象上失败了:
import kotlin.reflect.KMutableProperty
import kotlin.reflect.full.companionObject
import kotlin.reflect.full.memberProperties
class WithProperty {
lateinit var prop: String
companion object {
lateinit var companionProp: String
}
fun test() = "$companionProp $prop"
}
fun main(args: Array<String>) {
val obj = WithProperty()
val prop = obj::class.memberProperties.filter { it.name == "prop" }.first()
if (prop is KMutableProperty<*>) {
prop.setter.call(obj, "world")
}
val companion = obj::class.companionObject
if (companion != null) {
val companionProp = companion.memberProperties.filter { it.name == "companionProp" }.first()
if (companionProp is KMutableProperty<*>) {
companionProp.setter.call(companionProp, "hello") // <-- what must go here as first argument?
}
}
println(obj.test())
}
调用普通属性的setter函数效果正常,但是当我调用
companionProp.setter.call(companionProp, "hello")
时,出现了如下异常:
请问我应该将什么作为Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
call()
的第一个参数才能成功?
编辑:我将companionProp
作为第一个参数写入了代码中,但显然是错误的,实际上我已经尝试过使用companion
对象,但也没有成功。
obj::class.companionObjectInstance
,因为在我的实际代码中,我不知道真正的类是什么。 - P.J.Meisch