gpt4 book ai didi

java - Constructor.newInstance 与 Class.newInstance 与 SecurityManager

转载 作者:搜寻专家 更新时间:2023-11-01 03:56:00 26 4
gpt4 key购买 nike

在 Java 中,当存在拒绝访问检查抑制的 SecurityManager 时,Constructor 的 newInstance 方法起作用,而 Class 的 newInstance 抛出 SecurityException。这是一个例子:

import java.lang.reflect.ReflectPermission;
import java.security.Permission;

public class Test {
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())) {
throw new SecurityException();
}
}
});

String.class.getConstructor().newInstance(); // works
String.class.newInstance(); // throws SecurityException
}
}

运行它会产生:

Exception in thread "main" java.lang.SecurityException
at Test$1.checkPermission(Test.java:10)
at java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject.java:125)
at java.lang.Class$1.run(Class.java:351)
at java.security.AccessController.doPrivileged(Native Method)
at java.lang.Class.newInstance0(Class.java:348)
at java.lang.Class.newInstance(Class.java:325)
at Test.main(Test.java:16)

Class.newInstance 的 JavaDoc说它在 SecurityManager 上调用 checkMemberAccess 和 checkPackageAccess,但我不知道为什么它会调用 setAccessible .这种行为差异是否有理由?

我正在使用:

java version "1.6.0_20"
OpenJDK Runtime Environment (IcedTea6 1.9.5) (ArchLinux-6.b20_1.9.5-1-x86_64)
OpenJDK 64-Bit Server VM (build 17.0-b16, mixed mode)

最佳答案

Class.newInstance() 调用 SecutrityManager.checkMemberAccess(this, Member.PUBLIC),这在默认情况下会授予所有公共(public)成员访问权限。 checkPermission() 仅在相关成员不是公开时被调用(通过 checkMemberAccess())。

因此,您对 checkPermission() 的覆盖不会影响对公共(public)成员的访问。您需要覆盖 checkMemberAccess()

这里是来自 Class 的 Javadocs 的相关引述:

(newInstance() fails if) invocation of s.checkMemberAccess(this, Member.PUBLIC) denies creation of new instances of this class

SecurityManager :

The default policy (of checkMemberAccess()) is to allow access to PUBLIC members, as well as access to classes that have the same class loader as the caller. In all other cases, this method calls checkPermission() ...

关于java - Constructor.newInstance 与 Class.newInstance 与 SecurityManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4908986/

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