运行以下代码,我在getPackage()行收到一个StackOverflowError。
如果我无法访问getPackage()来检查程序包,该如何只授予我想要的程序包中的类的权限?

package myPkg.security;

import java.security.Permission;

import javax.swing.JOptionPane;

public class SimpleSecurityManager extends SecurityManager {

    @Override
    public void checkPermission(Permission perm) {
 Class<?>[] contextArray = getClassContext();
 for (Class<?> c : contextArray) {
     checkPermission(perm, c);
 }
    }

    @Override
    public void checkPermission(Permission perm, Object context) {
 if (context instanceof Class) {
     Class clazz = (Class) context;
     Package pkg = clazz.getPackage(); // StackOverflowError
     String name = pkg.getName();
     if (name.startsWith("java.")) {
  // permission granted
  return;
     }
     if (name.startsWith("sun.")) {
  // permission granted
  return;
     }
     if (name.startsWith("myPkg.")) {
  // permission granted
  return;
     }
 }
 // permission denied
 throw new SecurityException("Permission denied for " + context);
    }

    public static void main(String[] args) {
 System.setSecurityManager(new SimpleSecurityManager());
 JOptionPane.showMessageDialog(null, "test");
    }

}

最佳答案

解决了!只需添加到第一个checkPermission方法的开头:

if (perm instanceof FilePermission) {
    if (perm.getActions().equals("read")) {
    // grant permission
    return;
    }
}

关于java - SecurityManager StackOverflowError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2510683/

10-10 02:07