Modifying final fields in Java
Compile-time constants are inlined (at javac compile-time). See the JLS, in particular 15.28 defines a constant expression and 13.4.9 discusses binary compatibility or final fields and constants.
If you make the field non-final or assign a non-compile time constant, the value is not inlined. For instance:
private final String stringValue = null!=null?"": "42";
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)