Modifying final fields in Java

前端 未结 5 2008
故里飘歌
故里飘歌 2020-12-13 00:07

Let\'s start with a simple test case:

import java.lang.reflect.Field;

public class Test {
  private final int primitiveInt = 42;
  private final Integer wra         


        
5条回答
  •  -上瘾入骨i
    2020-12-13 00:34

    In my opinion this is even worse: A colleague pointed to the following funny thing:

    @Test public void  testInteger() throws SecurityException,  NoSuchFieldException, IllegalArgumentException, IllegalAccessException  {      
        Field value = Integer.class.getDeclaredField("value");      
        value.setAccessible(true);       
        Integer manipulatedInt = Integer.valueOf(7);      
        value.setInt(manipulatedInt, 666);       
        Integer testInt = Integer.valueOf(7);      
        System.out.println(testInt.toString());
    }
    

    By doing this, you can change the behaviour of the whole JVM you are running in. (of course you can change only the values for the values between -127 and 127)

提交回复
热议问题