简体   繁体   中英

java: boolean instanceOf Boolean?

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"

因为原始的' true '将被AutoboxedBoolean并且是一个Object

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM