javaandroidkotlinreflectionkotlin-reflect

Java/Android/Kotlin: Reflection on private Field and call public methods on it


Is it possiable to use reflection to access a object's private field and call a public methods on this field?

i.e

class Hello {
   private World word
}

class World {
   public BlaBlaBla foo()
}

Hello h = new Hello()

World world = reflect on the h


// And then 

world.foo()

Solution

  • It’s possible to make private fields accessible using reflection. The following examples (both written in Kotlin) show it...

    Using Java Reflection:

    val hello = Hello()
    val f = hello::class.java.getDeclaredField("world")
    f.isAccessible = true
    val w = f.get(hello) as World
    println(w.foo())
    

    Using Kotlin Reflection:

    val hello = Hello()
    val f = Hello::class.memberProperties.find { it.name == "world" }
    f?.let {
        it.isAccessible = true
        val w = it.get(hello) as World
        println(w.foo())
    }