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 istrue
,false
, abyte
, or achar
in the range\u0000
to\u007f
, or anint
orshort
number between-128
and127
(inclusive), then letr1
andr2
be the results of any two boxing conversions ofp
. It is always the case thatr1 == 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).