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

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

使用普通的Java代码,我们无法访问类外的私有构造函数或私有方法。 但是通过使用reflection,我们可以访问Java类中的任何私有方法和构造函数。

那么我们如何为Java代码提供安全保障呢?

使用SecurityManager和足够严格的安全策略运行应用程序。

本教程中有一个简短的摘要和安全文档中的大量信息。

在所有私有方法/构造函数中添加checkPermission()方法。 checkPermission使用callerClass=selfClass sun.reflect.Reflection.getCallerClass(int n)通过assert callerClass=selfClass

getCallerClass返回方法的类realFramesToSkip构成堆栈(从零开始),忽略与java.lang.reflect.Method.invoke()相关的框架及其实现。 第一帧是与此方法关联的帧,因此getCallerClass(0)返回getCallerClass(0)的Class对象。

 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(); } } } 

你可以尝试测试reflection,它会失败:

 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(); } } 

您(作为相关代码的开发人员)无法做到这一点。

运行应用程序的最终用户可以安装禁止reflection的SecurityManager。