Bru*_*uno 9 java reflection securitymanager policies
关于这个问题,我一直在阅读关于Stackoverflow的很多问题,但无法找到解决方案或解决我的问题.如果已经有人,如果有人提示,我将不胜感激......
我的问题/问题是,是否可以完全禁用不值得信赖的代码的反射?功能如getDeclaredMethods()(见test.java).我已经有了一个Java安全管理器,如果代码试图写/读/等,它会抛出安全例外....
如果有可能,有人可以告诉我怎么样?
布鲁诺
test.java
TestClass cls = new TestClass();
Class c = cls.getClass();
// returns the array of Method objects
Method[] m = c.getDeclaredMethods();
for(int i = 0; i < m.length; i++) {
System.out.println("method = " + m[i].toString());
}
Run Code Online (Sandbox Code Playgroud)
扩展您的 SecurityManager 并让它检查ReflectPermission和RuntimePermission。然后你要决定调用者是否有 Reflection 的权限:
@Override
public void checkPermission(Permission perm) {
if (perm instanceof ReflectPermission) {
// called for Method.setAccessible(true)
// determine whether caller is permitted using getClassContext()
}
if (perm instanceof RuntimePermission) {
if (perm.implies(new RuntimePermission("accessDeclaredMembers"))) {
// called for Class.getDeclardFields()
System.out.println("getDeclaredFields() called");
}
}
Run Code Online (Sandbox Code Playgroud)
所以我不直接使用checkPermission()解决问题。我的解决方法是检查是否访问了java.lang.reflect包。
@Override
public void checkPackageAccess(String pkg){
// don't allow the use of the reflection package
if(pkg.equals("java.lang.reflect")){
throw new SecurityException("Reflection is not allowed!");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2977 次 |
| 最近记录: |