Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 634
TeeTracker Avatar asked Jan 08 '18 22:01

TeeTracker


People also ask

Can reflection access private methods?

You can access the private methods of a class using java reflection package.

How do you call private method on Kotlin?

To access a private method you will need to call the Class. getDeclaredMethod(String name, Class[] parameterTypes) or Class. getDeclaredMethods() method. The methods Class.

Can Java reflection API access private fields and methods of a 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.


1 Answers

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())
}
like image 128
s1m0nw1 Avatar answered Sep 20 '22 08:09

s1m0nw1