Sunday 19 May 2013

Accesing private variables using Reflection API

Reflection API in Java comes very handy to test class variables and methods at runtime. You can call it a type of hack as it violates the principle of Data Encapsulation. Let us see a code that demonstrates how can we access private variables using Reflection API and even edit it.

Code :


public class Someclass {
    private String name = "John";

}

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String args[]) throws Exception
    {
       
Someclass myClass = new Someclass();
        Field fs = myClass.getClass().getDeclaredField("name");
        fs.setAccessible(true);
        System.out.println("Variable is " + fs.getName() + " and value is " + fs.get(myClass));
        fs.set(myClass, "Sam");
        System.out.println("Variable is " + fs.getName() + " and value is " + fs.get(myClass));
    }
}

Output :  



Explanation : 

          Note that the private variable name is in the Someclass class and our main method is in the Test class. According to OOP principles we should not be able to access the private variable name. Using the instance of the class myClass we get the declared field with name name. Then we set it accessible property to true. Then we can access it and print it(as shown in the output). Moreover we can also change it's value using Reflection API. fs.set(myClass, "Sam") method does that.

For more details you can refer to it's documentation.
  
t> UA-39527780-1 back to top