Created
August 10, 2020 03:23
-
-
Save pfmiles/2e6fd827dd9106dbaa201e5a78493f07 to your computer and use it in GitHub Desktop.
使得private final字段能够被反射设置
This file contains hidden or 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 void makeSettable(Field f) { | |
try { | |
Field modifiersField = Field.class.getDeclaredField("modifiers"); | |
modifiersField.setAccessible(true); | |
modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL); | |
f.setAccessible(true); | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
注意:这段代码的调用应放置于任何针对传入field的get或set操作之前,否则缓存会让上述操作看上去失效了