Accessing private Fields and private Methods (Hacking A Class) in Java
In Java, by using the Reflection API, found in the java.lang.reflect package, you can access private fields and methods of another class. It is not even that difficult. This can be very handy during unit testing. If you try to access a field and a method, of an applet, then you will need to make a change in the SecurityManager setting. One Important thing is that this will work only when the code is running standalone, as in a Java application.
Access fields value of other class
There are two methods. The first one is Class.getDeclareField(obj)String obj and the second is Class.getDeclareFields(). Both of the methods only return public fields, so they would not work. So, you use setAccessible() method, which has a default value of false, but you can set it to true.
Example
- import java.lang.reflect.*;
- // this is the class which contain private fields name as
- public class PrivateObject
- {
- private String privateString = null;
- public PrivateObject(String privateString)
- {
- this.privateString = privateString;
- }
- }
- class PrivateTest
- {
- public static void main(String arg[])
- {
- try{
- PrivateObject privateObject = new PrivateObject(" you Successfully access the Private data Value of a class");
- // this is way to access the field of which class you want to access private data member.
- Field privateStringField = PrivateObject.class.getDeclaredField("privateString");
- // this setAccessible method has by default value false but you change it as true.
- privateStringField.setAccessible(true);
- // By using get method you access the field value and it type cast in String form.
- String fieldValue = (String) privateStringField.get(privateObject);
- System.out.println("fieldValue = " + fieldValue);
- }catch(Exception e)
- {
- System.out.println(e);
- }
- }
- }
OUTPUT
You can see that the private string is accessed by another class named PrivateTest.

Access Method of other class
There are two methods. The first one is Class.getDeclareMethod(String obj, Class[] parameter types ) and the second is Class.getDeclareMethods( ). Both of the methods only return public Methods, so they would not work. So, you can use the setAccessible() method which has a default value of false, but you set it to true.


Join the conversation! Your thoughts help the community grow.