gpt4 book ai didi

java - 为什么通过反射调用时自动装箱不使用 valueOf()?

转载 作者:IT老高 更新时间:2023-10-28 21:02:04 25 4
gpt4 key购买 nike

据我了解,以下代码应打印 "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 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 r<sub>1</sub> and r<sub>2</sub> be the results of any two boxing conversions of p. It is always the case that r<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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com