Last Updated: February 25, 2016
·
2.703K
· 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.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

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