繁体   English   中英

Java 反射:设置最终字段不起作用

[英]Java Reflection: setting a final field isn't working

因此,我使用一些有用的方法创建了一个ReflectUtil类,这些方法允许我以快速简单的方式访问 java 反射 API。 基于,方法forceCall可以更改私有和最终字段的值。

这个例子工作得很好:

ReflectUtil.forceCall(Boolean.class, null, "FALSE", true);
System.out.println(String.format("Everything is %s", false));

输出是: Everything is true (所以我的方法有效)。

但这不起作用(如果我在没有 ReflectUtil 类的情况下尝试它也不起作用):

public class JustForTestingPurposes {
    private static final String field = "no";

    public static void main(String[] args) throws Exception {
        ReflectUtil.forceCall(JustForTestingPurposes.class, null, "field", "yes");
        System.out.println(String.format("Is this working? %s", field));
    }

}

输出是: Is this working? no Is this working? no

我想,也许是因为java分配值的方式,所以我在执行main方法中的代码之前添加了1秒的睡眠,但没有成功。

这就是常量在 Java 中的工作方式。

编译 java 程序时,所有对编译时常量的引用(使用文字或<Classname>.class或类似的)都将替换为常量本身。

您应该能够通过将其分配给方法的返回值或使用new运算符来绕过它(以下示例包含两者):

private static final String field = getNo();
private String getNo(){
    return new String("no");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM