我有点困惑:我有一个函数,它接受一个对象作为参数。但是,如果我只是传递一个基元,甚至将布尔型基元识别为布尔型对象,编译器也不会报错。为什么会这样呢?
public String test(Object value)
{
if (! (value instanceof Boolean) ) return "invalid";
if (((Boolean) value).booleanValue() == true ) return "yes";
if (((Boolean) value).booleanValue() == false ) return "no";
return "dunno";
}
String result = test(true); // will result in "yes"发布于 2010-08-30 21:20:28
因为原语'true‘将被到Boolean,并且它是一个Object。
发布于 2010-08-30 21:24:03
就像之前的答案所说的,这叫做自动装箱。
实际上,在编译时,javac会将boolean原始值转换为Boolean对象。注意,通常情况下,由于以下代码的原因,反向转换可能会生成非常奇怪的NullPointerException
Boolean b = null;
if(b==true) <<< Exception here !您可以查看JDK documentation以获取更多信息。
发布于 2010-08-30 21:23:11
方法的这一部分:
if (((Boolean) value).booleanValue() == true ) return "yes";
if (((Boolean) value).booleanValue() == false ) return "no";
return "dunno";可以替换为
if (value == null) return "dunno";
return value ? "yes" : "no";https://stackoverflow.com/questions/3600686
复制相似问题