Kotlin Java Private Field Access Extension Feature

I would like to access a private Java field when using the Kotlin extension function .

Suppose I have a Java class ABC. ABChas only one private field mPrivateField. I would like to write an extension function in Kotlin that uses this field for any reason.

public class ABC {
    private int mPrivateField;

}

Kotlin function :

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

The error I get is:

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

Any way around this limitation?

+18
source share
4 answers

- , , :

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

field.isAccessible = true

Int by Field # getInt , :

val it: ABC = TODO()

val value = field.getInt(it)

, :

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

. . ,

fun String.foo() {
  println(this)
}

:

public static void foo(String $receiver) {
  System.out.println($receiver);
}

, $receiver, , , .

, , .

+8

, nhaarman . , , (.. ABC)

, 2017 .

fun ABC.testExtFunc() {
    val canIAccess = this.getmPrivateField()
}

fun ABC.getmPrivateField() : Int {
    val field = this.javaClass.declaredFields
            .toList().filter { it.name == "mPrivateField" }.first()
    field.isAccessible = true
    val value = field.get(this)
    return value as Int
}
+3

holi-java :

fun<T: Any> T.accessField(fieldName: String): Any? {
    return javaClass.getDeclaredField(fieldName).let { field ->
        field.isAccessible = true
        return@let field.get(this)
    }
}

val field = <your_object_instance_with_private_field>
                .accessField("<field_name>")
                    as <object_type_of_field_name>

:

class MyClass {

    private lateinit var mObject: MyObject

}

val privateField = MyClass()
                .accessField("mObject")
                    as MyObject

+1

Source: https://habr.com/ru/post/1681565/


All Articles