简体   繁体   English

如何限制开发人员使用反射来访问Java中的私有方法和构造函数?

[英]How to restrict developers to use reflection to access private methods and constructors in Java?

How to restrict developers to use reflection to access private methods and constructors in Java? 如何限制开发人员使用反射来访问Java中的私有方法和构造函数?

Using normal Java code we can't access private constructors or private methods outside of a class. 使用普通的Java代码,我们无法在类外部访问私有构造函数或私有方法。 But by using reflection we can access any private methods and constructors in a Java class. 但是通过使用反射,我们可以访问Java类中的任何私有方法和构造函数。

So how can we give security to our Java code? 那么,如何为Java代码赋予安全性呢?

Run your application using a SecurityManager and a sufficiently restrictive security policy . 使用SecurityManager和足够严格的安全策略运行您的应用程序。

There's a short summary in the tutorial and extensive information in the security documentation . 教程中简短摘要, 安全文档中有大量信息。

Add checkPermission() method in all of your private method/constructor. 在所有私有方法/构造函数中添加checkPermission()方法。 checkPermission using sun.reflect.Reflection.getCallerClass(int n) by assert callerClass=selfClass . 通过assert callerClass=selfClass sun.reflect.Reflection.getCallerClass(int n)callerClass=selfClass

The getCallerClass returns the class of the method realFramesToSkip frames up the stack (zero-based), ignoring frames associated with java.lang.reflect.Method.invoke() and its implementation. getCallerClass返回方法realFramesToSkip框架类(从零开始),而忽略与java.lang.reflect.Method.invoke()及其实现相关联的框架。 The first frame is that associated with this method, so getCallerClass(0) returns the Class object for sun.reflect.Reflection . 第一帧是一个与该方法相关联,因此getCallerClass(0)返回该类对象sun.reflect.Reflection

public class PrivateConstructorClass {

    private PrivateConstructorClass() {
        checkPerMission();
              //you own code go below
    }

    void checkPerMission() {
        Class self = sun.reflect.Reflection.getCallerClass(1);
        Class caller = sun.reflect.Reflection.getCallerClass(3);
        if (self != caller) {
            throw new java.lang.IllegalAccessError();
        }
    }
}

You can try to test reflect, it will fail: 您可以尝试测试反射,它将失败:

public class TestPrivateMain {

    Object newInstance() throws Exception {

        final Class<?> c = Class.forName("package.TestPrivate");

        final Constructor<?> constructor = c.getDeclaredConstructor();
        constructor.setAccessible(true);
        return constructor.newInstance();

    }

    public static void main(String[] args) throws Exception {
        Object t = new TestPrivateMain().newInstance();
    }
} 

You (as the developer of the code in question) cannot do that. 您(作为相关代码的开发人员)无法做到这一点。

The end user, who runs the application, could install a SecurityManager that forbids reflection. 运行该应用程序的最终用户可以安装一个禁止反射的SecurityManager。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM