请拷贝以下两个类,然后执行
类一:
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);
}
static void setFinalStaticField( Field field, Object newValue) throws Exception {
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set( null , newValue);
}
static void setFinalStaticString( Field field, Object newValue) throws Exception {
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 \n", Boolean.TYPE); // "Everything is true"
setFinalStaticField(TestFinalField.class.getField("finalField") , 99999);
System.out.println("finalField: " + TestFinalField.finalField);
setFinalStaticString(TestFinalField.class.getField("finalString") , "ccccc");
System.out.println("finalField: " + TestFinalField.finalString);
}
}
类二:
public class TestFinalField {
public static final int finalField = new Integer(1);
public static final String finalString = getString();
//public static final String finalString = "aaaaa"; 这样赋值修改不了,有办法修改的兄弟请指点,谢谢!
public static final Boolean finalBoolean = false;
public static void main(String[] args) {
// TODO Auto-generated method stub
// TestFinalField.finalField = new Integer(1234);
}
private static String getString(){
String str = new String("aaaaa");
// String str = "bbbbb";
return str;
}
}