Reflection - getFields doesn't works with inheritance?


#1

Hello, I have a sample that works in java but doesn’t works after converting it in Kotlin:

fun main(args: Array<String>) {
    val a = A()
    a.init()
    System.out.println(a.foo) //prints 0, but in java it prints 1
}

class A : B() {
//    @Throws(IllegalAccessException::class)
fun init() {
    for (field in B::class.java.fields) {
        field.setByte(this, 1.toByte())
    }
}
}

open class B {
var foo: Byte = 0
private val bar: Byte = 0
}

#2

It works only with
class.java.declaredFields
and
field.isAccessible = true
but it’s not the same way


#3

The Java fields for both foo and bar are private. If you want to expose a Kotlin property as a public Java field, you need to annotate it as @JvmField as described here.


#4

thanks