包的最终变量可以通过反射更改吗? [英] Can a package final variable be changed through reflection?

查看:98
本文介绍了包的最终变量可以通过反射更改吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过反射更改包最终变量吗?

Can a package final variable be changed through reflection?

说我有这个:

public class Widget {
  final int val = 23;
}

如果可以访问,可以通过反射更改val吗?

Can the val be changed through reflection if made accessible?

如果是这样,有没有办法在不使用安全管理器的情况下防止这种情况发生?

If so, is there any way to prevent it that without using the security manager?

推荐答案

结果是,更改最终成员会使反射获得的值不同于常规代码返回的值!这很吓人.

Turns out, changing final members causes reflection-obtained values to differ from values returned by regular code! This is quite scary.

import java.lang.reflect.Field;

public class Test {

    private static final class Widget {
        private final int val = 23;

        public int getVal() {
            return val;
        }
    }

    public static void main(String[] args) throws Exception {
        Widget w = new Widget ();

        Field m = Widget.class.getDeclaredField("val");

        m.setAccessible(true);

        m.set(w, 233);

        Field m1 = Widget.class.getDeclaredField("val");
        m1.setAccessible(true);


        System.out.println(m.get(w)); /// PRINT 233
        System.out.println(w.getVal()); /// PRINT 23
        System.out.println(m1.get(w)); /// PRINT 233

    }
}

这篇关于包的最终变量可以通过反射更改吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆