提问人:ceving 提问时间:10/11/2013 最后编辑:Rohit Jainceving 更新时间:8/23/2016 访问量:3118
Java 中的“(Object)null”和“null”有什么区别?[复制]
What is the difference between "(Object)null" and "null" in Java? [duplicate]
问:
请看以下示例:
class nul
{
public static void main (String[] args)
{
System.out.println (String.valueOf((Object)null));
System.out.println (String.valueOf(null));
}
}
第一个写入,但第二个抛出 .println
null
NullPointerException
为什么只有第二行值得例外?两者之间有什么区别?Java 中有真假之分吗?null
null
null
答:
第一次调用将调用 String.valueOf(Object)
方法,因为您已显式类型转换为引用。相反,第二个方法将调用重载的 String.valueOf(char[])
方法,因为它比参数更具体。null
Object
char[]
Object
null
此方法还有其他重载版本接受基元参数,但这些参数与参数不匹配。null
来自 JLS §15.12.2:
可能有不止一种这样的方法,在这种情况下,最 选择特定的一个。的描述符(签名加返回类型) 最具体的方法是在运行时用于执行该方法的方法 遣。
如果某个方法通过子类型适用,则该方法适用 (§15.12.2.2),适用于方法调用转换 (§15.12.2.3), 或者它是一种适用的可变方法 (§15.12.2.4)。
[...]
如果在其中一个 适用性测试的三个阶段,那么最具体的一个是 选择,如第 §15.12.2.5 节所述。
现在检查这两种方法的源代码:
// This won't throw NPE for `obj == null`
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
// This will throw `NPE` for `data == null`
public static String valueOf(char data[]) {
return new String(data);
}
评论
null
char[]
Object
valueOf
Object
null
null
char[]
String
.
static
#
instance
Java 中有很多重载方法。此外,在 Java 中具有任何和所有类型,因此任何类型(不是基元)都可以是 .String.valueOf
null
null
因此,当您调用时,您将调用将 as use 显式转换为 .(String.valueOf((Object)null)
valueOf
Object
null
Object
在第二个示例中,您没有显式地将 转换为任何特定类型,因此实际上您使用 a 调用该方法,该方法会引发 NPE。null
valueOf
char[]
摘自 JLS §15.12.2
第二步在上一步中确定的类型中搜索 成员方法。此步骤使用方法的名称和 参数表达式,用于查找两个可访问的方法 和适用,即可以正确调用的声明 给定的参数。
可能有不止一种这样的方法,在这种情况下,最 选择特定的一个。的描述符(签名加返回类型) 最具体的方法是在运行时用于执行该方法的方法 遣。
在这种情况下,它比没有进行显式强制转换时调用更具体。char[]
Object
null
评论
null
Although I accepted already an answer I would like to add the exact answer to the question, because the two answers concentrate on explaining the trap I walked into.
The difference between and is that the type of the first is forced to but the type of the second is not, as one could think, forced to . Instead it could also be an array instead of an object.(Object)null
null
Object
Object
So the conclusion is: pass instead of as an argument to a method to be sure to get exactly the method working on objects instead of any other method working on arrays.(Object)null
null
评论