Created
November 13, 2017 10:35
-
-
Save trydofor/fc98f1baedf2cef616a57fa2f2123b3c to your computer and use it in GitHub Desktop.
Java 反射 private final字段
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
Java 中对final 字段的修改,有很多黑魔法。 | |
org/apache/commons/lang3/reflect | |
https://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection/31268945#31268945 | |
# System.in,out,err允许重定向 | |
``` java | |
import java.lang.reflect.*; | |
public class EverythingIsTrue { | |
static void setFinalStatic(Field field, Object newValue) throws Exception { | |
field.setAccessible(true); | |
Field modifiersField = Field.class.getDeclaredField("modifiers"); | |
modifiersField.setAccessible(true); | |
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); | |
field.set(null, newValue); | |
} | |
public static void main(String args[]) throws Exception { | |
setFinalStatic(Boolean.class.getField("FALSE"), true); | |
System.out.format("Everything is %s", false); // "Everything is true" | |
} | |
} | |
``` | |
# private static final | |
# private final | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment