Java 中的 SecurityManager 有没有办法根据调用 setAccessible() 的详细信息选择性地授予 ReflectPermission("suppressAccessChecks") ?我看不出有什么办法可以做到这一点。
对于某些沙盒代码,允许调用 setAccessible() 反射 API 非常有用(例如运行各种动态 JVM 语言),但仅在源自沙盒代码的类的方法/字段上调用 setAccessible() 时。
如果不可能的话,除了选择性授予 ReflectPermission("suppressAccessChecks") 之外,还有其他建议吗?如果 SecurityManager.checkMemberAccess() 有足够的限制,也许在所有情况下授予权限都是安全的?
最佳答案
也许查看调用堆栈就足以满足您的目的?像这样的东西:
import java.lang.reflect.ReflectPermission;
import java.security.Permission;
public class Test {
private static int foo;
public static void main(String[] args) throws Exception {
System.setSecurityManager(new SecurityManager() {
@Override
public void checkPermission(Permission perm) {
if (perm instanceof ReflectPermission && "suppressAccessChecks".equals(perm.getName())) {
for (StackTraceElement elem : Thread.currentThread().getStackTrace()) {
if ("Test".equals(elem.getClassName()) && "badSetAccessible".equals(elem.getMethodName())) {
throw new SecurityException();
}
}
}
}
});
goodSetAccessible(); // works
badSetAccessible(); // throws SecurityException
}
private static void goodSetAccessible() throws Exception {
Test.class.getDeclaredField("foo").setAccessible(true);
}
private static void badSetAccessible() throws Exception {
Test.class.getDeclaredField("foo").setAccessible(true);
}
}
关于java - java中的SecurityManager有没有办法选择性地授予ReflectPermission ("suppressAccessChecks")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53709444/