java: boolean instanceOf Boolean?

前端 未结 4 1523
一个人的身影
一个人的身影 2020-12-17 10:58

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 primiti

相关标签:
4条回答
  • 2020-12-17 11:03

    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";
    
    0 讨论(0)
  • 2020-12-17 11:07

    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.

    0 讨论(0)
  • 2020-12-17 11:09

    its called autoboxing - new with java 1.5

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

    0 讨论(0)
  • 2020-12-17 11:10

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

    0 讨论(0)
提交回复
热议问题