java: boolean instanceOf Boolean?

强颜欢笑 提交于 2019-12-18 04:38:11

问题


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"

回答1:


Because primitive 'true' will be Autoboxed to Boolean and which is a Object.




回答2:


Like previous answers says, it's called autoboxing.

In fact, at compile-time, javac will transform your boolean primitve value into a Boolean object. Notice that typically, reverse transformation may generate very strange NullPointerException due, as an example, to the following code

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

You can take a look at JDK documentation for more infos.




回答3:


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



回答4:


its called autoboxing - new with java 1.5

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



来源:https://stackoverflow.com/questions/3600686/java-boolean-instanceof-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!