Kotlin extension function access Java private field

kosiara - Bartosz Kosarzycki picture kosiara - Bartosz Kosarzycki · Jul 16, 2017 · Viewed 18.8k times · Source

I'd like to access Java's private field when using Kotlin extension function.

Suppose I have a Java class ABC. ABC has only one private field mPrivateField. I'd like to write an extension function in Kotlin which uses that field for whatever reason.

public class ABC {
    private int mPrivateField;

}

the Kotlin function would be:

private fun ABC.testExtFunc() {
    val canIAccess = this.mPrivateField;
}

the error I'm getting is:

Cannot access 'mPrivateField': It is private in 'ABC'

Any way of getting around that limitation?

Answer

holi-java picture holi-java · Jul 16, 2017

First, you need to obtain a Field and enable it can be accessible in Kotlin, for example:

val field = ABC::class.java.getDeclaredField("mPrivateField")

field.isAccessible = true

Then, you can read the field value as Int by Field#getInt from the instance of the declaring class, for example:

val it: ABC = TODO()

val value = field.getInt(it)

Last, your extension method is looks like as below:

private inline fun ABC.testExtFunc():Int {
    return javaClass.getDeclaredField("mPrivateField").let {
        it.isAccessible = true
        val value = it.getInt(this)
        //todo
        return@let value;
    }
}