据我了解,以下代码应打印 "true"
,但是当我运行它时,它会打印 "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);
}
}
根据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 letr<sub>1</sub>
andr<sub>2</sub>
be the results of any two boxing conversions ofp
. It is always the case thatr<sub>1</sub> == r<sub>2</sub>
.
但是,如果通过反射调用方法,装箱值总是通过 new PrimitiveWrapper()
创建.
请帮助我理解这一点。
最佳答案
invoke将总是返回一个新的Object
。任何返回的原语都被装箱。
...if the [return] value has a primitive type, it is first appropriately wrapped in an object.
您的问题是适本地地证明了术语的歧义。即在包装期间,它确实不使用 Boolean.valueOf(boolean) .
关于java - 为什么通过反射调用时自动装箱不使用 valueOf()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54087689/