Skip to content

Instantly share code, notes, and snippets.

@trydofor
Created November 13, 2017 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trydofor/fc98f1baedf2cef616a57fa2f2123b3c to your computer and use it in GitHub Desktop.
Save trydofor/fc98f1baedf2cef616a57fa2f2123b3c to your computer and use it in GitHub Desktop.
Java 反射 private final字段
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