我试图在自定义安全管理器中查找哪个类已动态请求权限。我无法找到任何帮助我获取调用类的代码库位置的API。以下是我试图做的事情,
我有一个试图写入文件的testApp类,
package test.ProfilingSecurityManager;
import java.io.PrintWriter;
public class TestApp {
public static void main(String [] args) throws Exception {
System.setSecurityManager(new NewProfilingSecurityManger());
PrintWriter writer = new PrintWriter("profile.txt");
writer.println("Test line");
writer.close();
}
}
自定义安全管理器中的重写方法如下:
public void checkPermission(final Permission permission) {
try {
// see what the parent security manager code says
super.checkPermission(permission);
}
catch (Exception e) {
// find the code base which requested this permission
// I can get the call stack here
Class [] sourceClasses = getClassContext();
Class invokingClass = sourceClasses[sourceClasses.length - 1];
// I can also get the accesscontrol context here
// using -AccessController.getContext()
// How do i find the codebase location of the class
// which needed this permission here
}
}
我需要在checkPermission方法中抛出异常时找到TestApp的代码库位置。 有人可以帮我解决这个问题吗?
由于
答案 0 :(得分:1)
如果你调用invokingClass.getProtectionDomain()。getCodeSource(),这将告诉你该类的加载位置。
但是,这只会告诉您访问检查失败时哪个类位于调用堆栈的底部。在您给出的示例中,这将是TestApp,但如果您尝试调试安全权限问题,则更好的方法是在java.security.debug
系统属性设置为access,failure
的情况下运行Java。当权限检查失败时,这将告诉您哪个类没有权限,从哪里加载,以及它具有哪些权限。