In Java, a method of setAccessible (true) using reflection is widely known as a means of changing the value of a private field that is normally inaccessible from the outside.
We will show you how to apply this method to dynamically change the final field.
Main.java
public class Main {
public static void main(String[] args) throws Exception {
TargetClass clazz = new TargetClass();
System.out.println("Before update: " + clazz.getTargetField()); // Before update: 1
Field targetField = clazz.getClass().getDeclaredField("TARGET_FIELD"); //Get the Field object for the access to be updated.
Field modifiersField = Field.class.getDeclaredField("modifiers"); //Since the Field class uses modifiers to determine the access of the field to be accessed, update this.
modifiersField.setAccessible(true); //The modifiers themselves are private, so make them accessible.
modifiersField.setInt(targetField,
targetField.getModifiers() & ~Modifier.PRIVATE & ~Modifier.FINAL); //Remove private and final from the modifiers of the Field object for update target access.
targetField.set(null, 1000); //Value update: 1 -> 1000
System.out.println("_People People People People_"); // _People People People People_
System.out.println("After update: > " + clazz.getTargetField() + " <"); // After update: > 1000 <
System.out.println("  ̄Y^Y^Y^Y ̄"); //  ̄Y^Y^Y^Y ̄
}
}
TargetClass.java
public class TargetClass {
private static final Integer TARGET_FIELD = 1;
public Integer getTargetField() {
return TARGET_FIELD;
}
}
In an environment where SecurityManager is enabled, private static final fields cannot be changed dynamically using the above method. Also, if you are inlined by compile-time optimization, you cannot change the value using the above method. (In this case, no error will occur.)
http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection
Recommended Posts