Boxing for primitives is not aligned with specifications – why?

  • A+
Category:Languages

To my understanding following code should print "true"

However, when I ran this program it is printing "false" as output

According to jls-5.1.7

"If the value p being boxed is an integer literal of type int between -128 and 127 inclusive , or the boolean literal true or false , or a character literal between '/u0000' and '/u007f' inclusive , then let a and b be the results of any two boxing conversions of p. It is always the case that a == b."

However in case of method called via reflection boxed value is always created via new PrimitiveWrapper().

 public class Test {     public static boolean testTrue() {         return true;     }      public static void main(String[] args) throws Exception {         Object trueResult = Test.class.getMethod("testTrue").invoke(null);             System.out.println(trueResult == Boolean.TRUE);      } } 

Please help me understand this.

 


invoke will always return a new Object. Any returned primitives are boxed.

...if the [return] value has a primitive type, it is first appropriately wrapped in an object.

Your issue is demonstrating the ambiguity of the term appropriately. i.e. during wrapping, it does not use Boolean.valueOf(boolean).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: