gpt4 book ai didi

java - SecurityManager 堆栈溢出错误

转载 作者:行者123 更新时间:2023-12-01 16:06:18 28 4
gpt4 key购买 nike

运行以下代码,我在 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 堆栈溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2510683/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com