gpt4 book ai didi

java - 删除 ctor 时通过反射设置私有(private)最终字段失败

转载 作者:行者123 更新时间:2023-11-30 07:50:02 25 4
gpt4 key购买 nike

假设我有以下类(class):

public class SomeClass {

private final int num;

public SomeClass(int num) {
this.num = num;
}

public int getNum() {
return num;
}

}

当我执行 this code 时设置 num 字段,一切正常:

SomeClass obj = new SomeClass(0);

final Field field = SomeClass.class.getDeclaredField("num");
field.setAccessible(true);
Field modField = Field.class.getDeclaredField("modifiers");
modField.setAccessible(true);
modField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(obj, 1);

System.out.println(obj.getNum()); // Prints 1 instead of the initial value 0.

但是,当我从 SomeClass 中删除构造函数时,它不再起作用并且 println 语句打印 0。

谁能解释这种行为?

最佳答案

让我们看看 Java doc对于 Field.set 方法:

If the underlying field is final, the method throws an IllegalAccessException unless setAccessible(true) has succeeded for this Field object and the field is non-static. Setting a final field in this way is meaningful only during deserialization or reconstruction of instances of classes with blank final fields, before they are made available for access by other parts of a program. Use in any other context may have unpredictable effects, including cases in which other parts of a program continue to use the original value of this field.

这意味着在您的示例中,如果您删除构造函数,则需要将最终字段初始化为某个值,从而使其非空白。在这种情况下,如果您使用反射更改最终字段,您可能会产生不可预测的效果,包括以下情况程序的哪些其他部分继续使用的原始值这个字段。

关于java - 删除 ctor 时通过反射设置私有(private)最终字段失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47983064/

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