加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java反射无法按预期工作

发布时间:2020-12-15 08:25:34 所属栏目:Java 来源:网络整理
导读:我只是编写了这段代码来测试一些东西,以便更好地理解反射. 这是ReflectionTestMain类: import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class ReflectionTestMain { public st
我只是编写了这段代码来测试一些东西,以便更好地理解反射.

这是ReflectionTestMain类:

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionTestMain {
    public static void main(String[] args) {
        try {
            ReflectionTest rt = new ReflectionTest();
            Class<ReflectionTest> c = ReflectionTest.class;
            Field f = c.getDeclaredField("value");
            f.setAccessible(true);
            f.set(rt,"text");
            Method m = c.getDeclaredMethod("getValue");
            m.setAccessible(true);
            String value = (String) m.invoke(rt);
            System.out.println(value);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

这是ReflectionTest类.

public class ReflectionTest {
    private final String value = "test";

    private String getValue() {
        return value;
    }
}

此代码打印测试但我希望它打印文本.这不起作用的原因是什么,我该如何解决?

解决方法

虽然变量已正确更新,但它不会传播到getValue()方法.

原因是编译器为您优化程序.

由于编译器知道变量值未更改,因此它将其编译为直接访问字符串池的内联访问,而不是通过变量.这可以通过在类文件上运行java -p来看到

这可以通过对字符串常量使用initizer块或构造函数来解决,或者使语句更复杂以“欺骗”编译器.

class ReflectionTest {


    // Use either
    private final String value;
    {
        value = "test";
    }
    // Or 
    private final String value;
    public ReflectionTest () {
        value = "test";
    }
    // Or
    private final String value = Function.identity().apply("test");
    // Or

    //   Do not replace with + as the compiler is too smart
    private final String value = "test".concat(""); 
    // Depending on your required performance/codestyling analyses

    private String getValue() {
        return value;
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读