Created
July 11, 2014 19:54
-
-
Save superckl/2953dc120ca3773e6d5b to your computer and use it in GitHub Desktop.
Reflecting a final field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static boolean setFinalStatic(final Class<?> clazz, final String field, final Object toPut, final boolean coverTracks){ | |
try { | |
final Field toSet = clazz.getDeclaredField(field); | |
final boolean access = toSet.isAccessible(); | |
toSet.setAccessible(true); | |
final boolean isFinal = (Modifier.FINAL & toSet.getModifiers()) == Modifier.FINAL; | |
final Field modifiers = Field.class.getDeclaredField("modifiers"); | |
final boolean accessModifiers = modifiers.isAccessible(); | |
modifiers.setAccessible(true); | |
modifiers.setInt(toSet, toSet.getModifiers() & ~Modifier.FINAL); | |
toSet.set(null, toPut); | |
if(coverTracks){ | |
if(isFinal) | |
modifiers.setInt(toSet, toSet.getModifiers() & Modifier.FINAL); | |
modifiers.setAccessible(accessModifiers); | |
toSet.setAccessible(access); | |
} | |
} catch (final Exception e) { | |
LogHelper.error("Failed to set static final field "+field+" in class "+clazz.getCanonicalName()+" to "+toPut+". coverTracks: "+coverTracks); | |
e.printStackTrace(); | |
return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment