Monday, 10 February 2014

Accessing Private Members of a Class

Normally You cannot access the private variables and methods of a Class,from outside of the class.
By Reflection API,gives us the facility to access them
The following program demonstrates the same
Demo.java
?
1
2
3
4
5
6
7
public class Demo {
    private String msg= "Satya";
    private String show() {
        System.out.println("show()::You cannot access me from outside");
        return "Java";
    }
}
AccessingPrivateVariable .java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class AccessingPrivateVariable
{
    public static void main(String[] args)throws IllegalAccessException,InvocationTargetException
    {
        Demo  demo = new Demo();
        //d.show();    //Compile time Error
        //String str=d.msg; //compile Time Error
        Class cls = demo.getClass();//Points to Demo Class
        System.out.println("Accessing methods....");
        //get Access to all the method of class
        //since our Demo class has only 1 method,show().methods[] contains 1 element
        Method methods[] = cls.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++)
        {
            //Prints information about method
            System.out.println(methods[i].getReturnType()+" " +methods[i].getName());
            methods[i].setAccessible(true);//changing the accessiblity to true
            String flag1=(String)methods[i].invoke(demo);//calls show(),returns Object
            System.out.println(flag1 );
        }
        //  Prints all the field names & values
        System.out.println("Accessing Fields....");
        Field fields[] = cls.getDeclaredFields();//gets all fields
        for (int i = 0; i < fields.length; i++){
            //prints field name
            System.out.println("Field Name: " + fields[i].getName());
            fields[i].setAccessible(true);//making fields accessible
            String flag2=(String)fields[i].get(demo);//gets value of Demo.msg field
            System.out.println(flag2);
        }
    }
}

No comments:

Post a Comment