gpt4 book ai didi

java - 使用 Java 反射更新字段值

转载 作者:行者123 更新时间:2023-12-01 09:06:54 26 4
gpt4 key购买 nike

我引用了Change private static final field using Java reflection并编写以下代码来更新 String 类型静态最终字段值:

我有一个包含如下常量的类:

public final class Constants {

public static final String ACCEPTED = "A";
}

我尝试使用 Java Reflection 更新它的值,如下所示:

Field field = Constants.class.getDeclaredField("ACCEPTED");
field.setAccessible(true);

Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

String newValue = "B";
field.set(null, newValue);

使用上面的代码更新值后,我对其进行了如下测试:

String myUpdatedValue = Constants.ACCEPTED;

当我检查 Constants.ACCEPTED 时,显示的值是 "B",但是当我检查 myUpdatedValue 时,它显示作为“A”。无法理解道理。即使当我将此值作为参数传递给其他方法时,在该方法调用时它是“B”,但在被调用方法内它是“A”

最佳答案

引用the documentation :

Note: If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.

在您的情况下,Constants.ACCEPTED 就是这样一个编译时常量。因此,当编译代码时,所有对 Constants.ACCEPTED 的引用实际上都被替换为文字 "A"。您的代码在运行时操纵它的值,但这已经太晚了。

关于java - 使用 Java 反射更新字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41197334/

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