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()
You can access the private methods of a class using java reflection package.
To access a private method you will need to call the Class. getDeclaredMethod(String name, Class[] parameterTypes) or Class. getDeclaredMethods() method. The methods Class.
If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.
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())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With