Kotlin extension function access Java private field
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;
}
}
That is not possible by design. Extension functions essentially resolve to static functions with the receiver as its first parameter. Thus, an extension function
fun String.foo() {
println(this)
}
compiles to something like:
public static void foo(String $receiver) {
System.out.println($receiver);
}
Now it's clear to see you cannot access private member of $receiver
, since they're, well, private.
If you really want to access that member, you could do so using reflection, but you'll lose all guarantees.