我有一个带有private static final字段的类,不幸的是,我需要在运行时更改.
使用反射我得到这个错误: java.lang.IllegalAccessException: Can not set static final boolean field
有没有办法改变价值?
Field hack = WarpTransform2D.class.getDeclaredField("USE_HACK");
hack.setAccessible(true);
hack.set(null, true);
Run Code Online (Sandbox Code Playgroud) System.out被宣布为public static final PrintStream out.
但你可以打电话System.setOut()重新分配它.
咦?这怎么可能呢final?
(同一点适用于System.in和System.err)
更重要的是,如果你可以改变公共静态最终字段,那么这对于final给你的保证(如果有的话)意味着什么呢?(我从未意识到也没有预料到System.in/out/err表现为final变量)
以下是java.lang.System类中的代码(JDK版本1.6)
public final static PrintStream out = nullPrintStream(); //out is set to 'null'
private static PrintStream nullPrintStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
return null;
}
throw new NullPointerException();
}
Run Code Online (Sandbox Code Playgroud)
当我们System.out.println("Something");在代码中写入时,为什么即使'out'设置为'null'也不会得到NullPointerException
无论如何out将通过setOutSystem类中的以下方法设置
public static void setOut(PrintStream out) {
checkIO();
setOut0(out);
}
Run Code Online (Sandbox Code Playgroud)
Theyn为什么JLS需要nullPrintStream方法?