Java Reflection field get/set final fields

Introduction

Java reflection API allows us to modify a final field.

public void setAccessible(boolean flag)  
public static void setAccessible(AccessibleObject[] array, boolean flag) 

Here is an example program that modifies the private final field

import java.lang.reflect.Field;

class X {/*from   w w w. j a v  a  2 s .c om*/
   private final int pf = 0;
}

public class Main {
   public static void main(String args[]) throws Exception {
      X x = new X();
      Class c = x.getClass();
      Field f = c.getDeclaredField("pf");
      f.setAccessible(true);
      System.out.println("Before: pf = " + f.getInt(x));
      f.setInt(x, 4);
      System.out.println("After : pf = " + f.getInt(x));
   }
}



PreviousNext

Related