Using Kotlin reflection, how do I set a Kotlin Object’s member property?

  Kiến thức lập trình

I’m trying to use reflection to set a Kotlin Object’s val property. When I try the code below, I get an exception:

Can not set static final Foo field Person.foo to Biz
java.lang.IllegalAccessException: Can not set static final Foo field Person.foo to Biz

interface Foo {
    fun hello(): String
}

class Bar: Foo {
    override fun hello(): String {
        return "Bar"
    }
}

class Biz: Foo {
    override fun hello(): String {
        return "Biz"
    }
}

object Person {
    val foo: Foo = Bar()
}

fun main() {
    val person = Person
    val property = person::class.memberProperties.first { it.name == "foo" }
    val javaField = property.javaField!!
    javaField.isAccessible = true
    javaField.set(person, Biz()) // exception happens here
    println(Person.foo.hello())
}

Is there any way to have Person.foo.hello() return “Biz” instead of “Bar” via Kotlin or Java reflection APIs?

Thanks!

LEAVE A COMMENT