17

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"
4

4 回答 4

32

因为原始“ true”将被自动装箱Boolean并且是Object.

于 2010-08-30T13:20:27.653 回答
3

就像以前的答案所说,它被称为自动装箱。

实际上,在编译时,javac会将您的boolean原始值转换为Boolean对象。请注意,通常,NullPointerException由于以下代码,反向转换可能会产生非常奇怪的情况

Boolean b = null;
if(b==true) <<< Exception here !

您可以查看JDK 文档以获取更多信息。

于 2010-08-30T13:24:03.257 回答
2

这部分方法:

  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";
于 2010-08-30T13:23:10.950 回答
1

它称为自动装箱 - java 1.5 的新功能

http://download.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

于 2010-08-30T13:21:01.517 回答