Why does autoboxing not use valueOf() when invoking via reflection?

  • A+

To my understanding following code should print "true", but when I run it it prints "false".

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);     } } 

According to JLS §5.1.7. Boxing Conversion:

If the value p being boxed is true, false, a byte, or a char in the range /u0000 to /u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

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

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).


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