嗯,它确实适用于setAccessible.看到:
class A {
private String method1() {
return "Hello World!";
}
}
和
import java.lang.reflect.Method;
class B {
public static void main(String[] args) throws Exception {
System.setSecurityManager(new SecurityManager());
Class clazz = A.class;
Method m = clazz.getDeclaredMethod("method1");
m.setAccessible(true);
}
}
结果是
Exception in thread "main" java.security.AccessControlException: access denied ("java.lang.reflect.ReflectPermission" "suppressAccessChecks")
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.reflect.AccessibleObject.setAccessible(Unknown Source)
at B.main(B.java:8)
它可能对你不起作用的一个原因是,根据this post中的评论,它不能用于Java 1.5,但在6和之后工作.
编辑:要为特定的罐子拒绝它,您需要使用策略文件,例如:
// specific file
grant codeBase "file:/test/path/tools.jar" {
// no permissions for this one
};
// default to giving all
grant {
permission java.security.AllPermission;
};
有两种方法可以指定策略文件,或者将其作为默认值添加,或者仅提供指定的策略文件(source):
If you use
06004
(note the double equals) then just the specified policy file will be
used; all the ones indicated in the security properties file will be
ignored.
…或者实现自定义安全管理器,doesn’t look that hard.尽管我自己也没有这样做.