Tuesday 12 August 2014

Can I access private variables in Java ?

Yes. By using reflection, you can access private variables in Java.

Step 1: Get the class object.
Ex: Employee emp = new Employee();
Class myClass = emp.getClass();

Step 2: get the declared field.
Ex: Field myField = myClass.getDeclaredField("id")

Step 3: suppress Java language access checking by enabling the accessibility to true for this field.
Ex: myField.setAccessible(true);

Step 4: Set the field value.
class Employee {
    private int id, age;
    
    int getId(){
        return id;
    }
    
    int getAge(){
        return age;
    }
            
}

import java.lang.reflect.Field;

public class GetFields {
    
   public static void display(Employee emp){
       System.out.println("---------------------------");
       System.out.println("id : " + emp.getId());
       System.out.println("age : " + emp.getAge());
   }
   public static void main(String args[]) throws Exception{
       Employee emp = new Employee();
       Class myClass = emp.getClass();
       
       System.out.println("Setting id");
       Field myField = myClass.getDeclaredField("id");
       myField.setAccessible(true);
       myField.setInt(emp, 1);
       display(emp);
       
       System.out.println("Setting age");
       myField = myClass.getDeclaredField("age");
       myField.setAccessible(true);
       myField.setInt(emp, 26);
       display(emp);
   } 
}

Output
Setting id
---------------------------
id : 1
age : 0
Setting age
---------------------------
id : 1
age : 26

                                                 Home

No comments:

Post a Comment