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

标签 java reflection

我引用了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/

相关文章:

java - 支付网关集成时获取 SSLException

java - 寻找 GCD,Java 套接字编程

java - 跟踪服务之间调用的方法

c# - 复制两个具有不同 namespace 的相同对象(递归反射)

c# - 使用 Intellisense 和编译时检查提取属性名称以进行反射

java - 如何在运行时从java对象获取实例变量的行号

java - Hibernate:必须在调用 save() 之前手动分配此类的 id

java - 带有选择的基本加法和减法

c# - 有typeof的逆运算吗?

Java:反射、通用类型和未检查的转换