简体   繁体   English

java:boolean instanceOf Boolean?

[英]java: boolean instanceOf Boolean?

I'm a bit confused: I have a function, that takes an Object as argument. 我有点困惑:我有一个函数,它以Object作为参数。 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. 实际上,在编译时, javac会将你的boolean primitve值转换为一个Boolean对象。 Notice that typically, reverse transformation may generate very strange NullPointerException due, as an example, to the following code 请注意,通常,反向转换可能会生成非常奇怪的NullPointerException ,例如,由于以下代码

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

You can take a look at JDK documentation for more infos. 您可以查看JDK文档以获取更多信息。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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