Thursday 18 October 2012

How to access private variable outside using reflection


//Example of acessing private variable outside the class using reflection api.

package com.gaurav;
import java.io.File;

public class DisplayAllDrivesInSystem {
    private String accessPrivateVariableTest = "Welcome Gaurav";    
        -- We will acess this variable outside this class.
    public static void visitAllFiles(File dir) {
        if (dir.isDirectory()) {
          String[] children = dir.list();
          for (int i = 0; i < children.length; i++) {
            visitAllFiles(new File(dir, children[i]));
          }
        } else {
          System.out.println(dir);
        }
      }
    public static void main(String args[]){
        File dir = new File("C://Tomcat 5.5");
        File[] drives = File.listRoots();
        for(File i : drives){
                    System.out.println("Available Drives are-> "+i);
        }
        visitAllFiles(dir);
    }
}

// This is the another class where we will acess the private variable of above class using reflection api.


package com.gaurav; 
import java.lang.reflect.Field;

public class AccessPrivateVariableUsingReflection {
   
    public static void main(String args[]){
        try{
        @SuppressWarnings("rawtypes")
        Class c = Class.forName("DisplayAllDrivesInSystem");
        Field fields[] = c.getDeclaredFields();
       
        for(Field fld : fields){
            System.out.println("field values-->"+fld);
        }
        DisplayAllDrivesInSystem ref = new DisplayAllDrivesInSystem();
        c = ref.getClass();
        Field flds = c.getDeclaredField("accessPrivateVariableTest");
        flds.setAccessible(true);
        System.out.println("the private field value before change is-"+flds.get(ref));
        flds.set(ref, "Changed value Kumar Gaurav");
        System.out.println("Now the Private field Value after change is-"+flds.get(ref));
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment