String x = (String) null;
为什么这个说法没有例外?
String x = null;
System.out.println(x);
它输出null。但是. tostring()方法应该抛出空指针异常。
String x = (String) null;
为什么这个说法没有例外?
String x = null;
System.out.println(x);
它输出null。但是. tostring()方法应该抛出空指针异常。
当前回答
可以将null转换为任何引用类型。你也可以调用将空值作为参数处理的方法,例如System.out.println(Object),但是你不能引用空值并调用它的方法。
顺便说一句,有一个棘手的情况,似乎你可以调用空值的静态方法。
Thread t = null;
t.yield(); // Calls static method Thread.yield() so this runs fine.
其他回答
Println(Object)使用String.valueOf()
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Print(String)检查空值。
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
这种语言特性在这种情况下很方便。
public String getName() {
return (String) memberHashMap.get("Name");
}
如果memberHashMap.get("Name")返回null,您仍然希望上面的方法返回null而不抛出异常。不管类是什么,null都是null。
正如其他人所写的那样,您可以将所有内容转换为null。 通常,你不需要这样做,你可以这样写:
String nullString = null;
不用打石膏。
但在某些情况下,这种类型转换是有意义的:
A)如果你想确保一个特定的方法被调用,比如:
void foo(String bar) { ... }
void foo(Object bar) { ... }
如果你打字的话,情况就不一样了
foo((String) null) vs. foo(null)
b)如果你打算使用IDE来生成代码;例如,我通常写单元测试:
@Test(expected=NullPointerException.class)
public testCtorWithNullWhatever() {
new MyClassUnderTest((Whatever) null);
}
我在做TDD;这意味着“MyClassUnderTest”类可能还不存在。通过写下这些代码,我可以使用我的IDE首先生成新类;然后生成一个接受“Whatever”参数的“开箱即用”构造函数——IDE可以从我的测试中得出构造函数应该只接受一个Whatever类型的参数。
打印:
打印一个对象。由string . valueof (Object)方法生成的字符串被转换为字节
返回对象的值:
如果参数为null,则字符串等于"null";否则,返回obj.toString()的值。
当对象为空时,它将简单地返回值为“null”的字符串。
这在使用可能具有歧义的方法时非常方便。例如:JDialog具有以下签名的构造函数:
JDialog(Frame, String, boolean, GraphicsConfiguration)
JDialog(Dialog, String, boolean, GraphicsConfiguration)
我需要使用这个构造函数,因为我想设置GraphicsConfiguration,但我没有这个对话框的父项,所以第一个参数应该为空。使用
JDialog(null, String, boolean, Graphicsconfiguration)
是模棱两可的,所以在这种情况下,我可以通过将null转换为支持的类型之一来缩小调用:
JDialog((Frame) null, String, boolean, GraphicsConfiguration)