如何防止通过反射访问? [英] How to prevent access via reflection?

查看:51
本文介绍了如何防止通过反射访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java文档中,它提到使用 f.setAccessible(true)方法可以违反封装的原理.

In Java docs it mentioned that using f.setAccessible(true) method we can violate the principal of encapsulation.

但是,如果我正在编写具有完全安全性的任何类,例如带有私有变量的类,该如何防止通过反射访问它?

But if I am writing any class which has full security, for instance with a private variable, how can I prevent it from being accessed with reflection?

例如,我有一个带有完整安全实例变量的类:

For example I have a class with full secured instance variable:

public final class Immutable {
    private final int someVal;

    public Immutable(int someVal) {
        this.someVal = someVal;
    }

    public int getVal() {
        return someVal;
    }
}

但是我可以使用反射来修改该实例变量,如下所示:

But I can modify that instance variable using reflection like this:

public class Tester {
    public static void main(String[] args)
            throws NoSuchFieldException, SecurityException,
            IllegalArgumentException, IllegalAccessException {

        Immutable i = new Immutable(10);

        // output 10
        System.out.println(i.getVal());

        Field f = i.getClass().getDeclaredField("someVal");
        f.setAccessible(true);
        f.set(i, 11);

        // output is 11 which implies some value modified
        System.out.println(i.getVal());
    }
}

在我的代码中,如何防止不可变类被反射更改?

In my code, how can I prevent an immutable class being changed with reflection?

推荐答案

JVM具有内置的安全性机制,使您可以定义通过Java安全性策略文件进行编码的限制.Java安全管理器使用Java安全策略文件来实施一组授予类的权限.权限允许在JVM实例中运行的指定类允许或不允许某些运行时操作.如果启用Java安全管理器但未指定安全策略文件,则Java安全管理器将使用$ JAVA_HOME/jre/lib/security目录中java.security和java.policy文件中定义的默认安全策略.定义策略文件可以在这里找到 http://docs.oracle.com/javase/7/docs/technotes/guides/security/PolicyFiles.html

The JVM has security mechanisms built into it that allow you to define restrictions to code through a Java security policy file. The Java security manager uses the Java security policy file to enforce a set of permissions granted to classes. The permissions allow specified classes running in that instance of the JVM to permit or not permit certain runtime operations. If you enable the Java security manager but do not specify a security policy file, the Java security manager uses the default security policies defined in the java.security and java.policy files in the $JAVA_HOME/jre/lib/security directory. Defining your policy file can be found here http://docs.oracle.com/javase/7/docs/technotes/guides/security/PolicyFiles.html

这篇关于如何防止通过反射访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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