Sunday 15 May 2016

Change the value of final variable

By using reflections, you can change the value of final fields. Following step-by-step procedure explains how to change the value of final fields.

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 final int id, age;
    
    Employee(int id, int age){
      this.id = id;
      this.age = age;
    }
    
    Employee(){
      id = -1;
      age = -1;
    }
    
    int getId(){
        return id;
    }
    
    int getAge(){
        return age;
    }
            
}

import java.lang.reflect.Field;

public class Test {

  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 : -1
Setting age
---------------------------
id : 1
age : 26



Previous                                                 Next                                                 Home

No comments:

Post a Comment