Accessing private class members using reflection

We can access private fields and methods outside of class using reflection. Let’s see some example.

In this example, we will try to access the private field defined in the other class.

Output is –

—–get filed name defined in Employee class—-
Exception in thread “main” java.lang.IllegalAccessException: Class reflection1.Example3 can not access a member of class reflection1.Employee with modifiers “private”
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at reflection1.Example3.main(Example3.java:23)

 

Let’s see how we can access the private field using¬†setAccessible(true).

Output is –

—-Access private field using setAccessible(true)——
Ram
—–Access private methods using setAccessible(true)—–
even i am private method, you can access me outside of class using reflection

 

Top