Last Updated: February 25, 2016
· furikuri

Replace 'private static final'-Fields in Java

Normally it is not possible to set a new object to a 'private static final' field per Reflection. If you try this, you will get an IlleagaAccessException. Before you can access to a final field, you have to modify the 'modifiers' field in the Field class.

Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

After this little code snippet, you will be able to access to final fields.