[英]Java Reflection: setting a final field isn't working
So, I made a ReflectUtil
class with some useful methods that allow me to access the java reflection API in a fast and simple way.因此,我使用一些有用的方法创建了一个ReflectUtil
类,这些方法允许我以快速简单的方式访问 java 反射 API。 Based on this the method forceCall
can change the value of a private and final field.基于此,方法forceCall
可以更改私有和最终字段的值。
This example works absolutely fine:这个例子工作得很好:
ReflectUtil.forceCall(Boolean.class, null, "FALSE", true);
System.out.println(String.format("Everything is %s", false));
The output is: Everything is true
(so my method is working).输出是: Everything is true
(所以我的方法有效)。
But this just isn't working (it also doesn't work if i try it without my ReflectUtil class):但这不起作用(如果我在没有 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));
}
}
The output is: Is this working? no
输出是: Is this working? no
Is this working? no
I thought, maybe it's because of the way how java assigns values, so I added a 1 sec sleep before executing the code in the main method, with no success.我想,也许是因为java分配值的方式,所以我在执行main方法中的代码之前添加了1秒的睡眠,但没有成功。
This is how constants work in java.这就是常量在 Java 中的工作方式。
When a java program is compiled, all references to a compile-time-constant (using a literal or maybe <Classname>.class
or similar)are replaced with the constant itself.编译 java 程序时,所有对编译时常量的引用(使用文字或<Classname>.class
或类似的)都将替换为常量本身。
You should be able to bypass this by assigning it to the return value of a method or using the new
operator(the following example contains both):您应该能够通过将其分配给方法的返回值或使用new
运算符来绕过它(以下示例包含两者):
private static final String field = getNo();
private String getNo(){
return new String("no");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.