java:布尔instanceOf布尔?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3600686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java: boolean instanceOf Boolean?
提问by epegzz
I'm a bit confused: I have a function, that takes an Object as argument. But the compiler does not complain if I just pass a primitive and even recognizes a boolean primitive as Boolean Object. Why is that so?
我有点困惑:我有一个函数,它将对象作为参数。但是编译器不会抱怨我只是传递一个原语,甚至将一个布尔原语识别为布尔对象。为什么呢?
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"
回答by Jigar Joshi
回答by Riduidel
Like previous answers says, it's called autoboxing.
就像之前的答案所说的,它被称为自动装箱。
In fact, at compile-time, javacwill transform your booleanprimitve value into a Booleanobject. Notice that typically, reverse transformation may generate very strange NullPointerExceptiondue, as an example, to the following code
实际上,在编译时,javac会将您的boolean原始值转换为Boolean对象。请注意,通常情况下,NullPointerException由于以下代码,逆向转换可能会产生非常奇怪的结果
Boolean b = null;
if(b==true) <<< Exception here !
You can take a look at JDK documentationfor more infos.
您可以查看JDK 文档以获取更多信息。
回答by Paul Tomblin
This part of the method:
这部分方法:
if (((Boolean) value).booleanValue() == true ) return "yes";
if (((Boolean) value).booleanValue() == false ) return "no";
return "dunno";
Could be replaced with
可以换成
if (value == null) return "dunno";
return value ? "yes" : "no";
回答by Adam Butler
its called autoboxing - new with java 1.5
它被称为自动装箱 - 新的 Java 1.5
http://download.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html
http://download.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

