以下是来自java.lang.System类(JDK版本1.6)的代码:
当我们在代码中写入
无论如何,'out'将通过System类中的以下
他们为什么需要
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();
}
当我们在代码中写入
System.out.println("Something");
时,即使'out'被设置为'null',为什么我们不会得到NullPointerException呢?无论如何,'out'将通过System类中的以下
setOut
方法进行设置。public static void setOut(PrintStream out) {
checkIO();
setOut0(out);
}
他们为什么需要
nullPrintStream
方法?
public final static PrintStream out = null;
。 - assyliasif
语句,编译器可能会意识到它总是返回null
并将out
编译为编译时常量,带来所有不良后果。 - Marko TopolnikcurrentTimeMillis()
方法返回的值超出了long
类型的最大值,所有在Java 7之前版本的虚拟机上运行的应用程序都将因错误而失败:java.lang.ExceptionInInitializerError Caused by java.lang.NullPointerException at java.lang.System.nullPrintStream(Unknown Source)
或类似的错误。 - gparyani