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

TeeTracker :

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()
s1m0nw1 :

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())
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=464242&siteId=1