SecurityManager StackOverflowError
Running the following code, I get a StackOverflowError at the getPackage() line. How can I grant permission just to classes inside package I wan开发者_StackOverflowt, if I can't access the getPackage() to check the package?
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");
}
}
Solved! Just add to the begin of the first checkPermission method:
if (perm instanceof FilePermission) {
if (perm.getActions().equals("read")) {
// grant permission
return;
}
}
If you just want to restrict packages, how about implementing checkPackageAccess and/or checkPackageDefinition instead the generic checkPermission?
精彩评论