2
 class FinalConcept
 {
   private final int number = 22;


   public static void main(String args[])
    { 
          try{
        FinalConcept obj  = new FinalConcept();      
        System.out.println("value of the x variable "+obj.number);


       Field obj1 = obj.getClass().getDeclaredField("number");
        obj1.setAccessible(true);
         obj1.setInt(obj,45); 

If I try to access the variable by field function then I get changed value

System.out.println("value of the x variable "+obj1.get(obj));//45

But if I try to access by the name of variable, I get the same value

System.out.println("value of x varialbe "+obj.x);//22

Why is this hapenning ?

IAmInPLS
  • 4,051
  • 4
  • 24
  • 57
  • 1
    Possible Solution : http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection – Pankaj Verma Jun 03 '16 at 07:27
  • I suspect that `x` just becomes a compile-time constant and directly inlined. But seriously, _why_ are you screwing with final variables like this? – Louis Wasserman Jun 03 '16 at 17:03

2 Answers2

0

Your variable in number is declared final, so it can't be modified. The object itself will keep always the same value.

SCouto
  • 7,808
  • 5
  • 32
  • 49
0

Its interesting, I tried to dig it out, and found one observation, If we change the filed "number" from int to Integer, then we get the exception:

Exception-> java.lang.IllegalArgumentException: Can not set final java.lang.Integer field HelloTestJava.number to (int)45

One reason which I observed is that, this behavior is with primitives (int, char, byte , short, boolean, float, double, long) only. There is no exception If we try to change the value of a final primitive field through the Field object.

The same exception I got when I take a final Boolean field and tried to change it through reflection(i.e. through Field object)

Exception->  java.lang.IllegalArgumentException: Can not set final java.lang.Boolean field HelloTestJava.number to (boolean)false

But one thing is for sure, that your object will always have the correct(not-changed) value, doesn't matter we are trying to modify the value through reflection.

pbajpai
  • 1,303
  • 1
  • 9
  • 24