gpt4 book ai didi

java - Class 的 getClassLoader() 什么时候抛出 SecurityException

转载 作者:行者123 更新时间:2023-12-02 11:19:47 26 4
gpt4 key购买 nike

来自 Class 的 getClassLoader() 中的文档,

If a security manager is present, and the caller's class loader is not null and the caller's class loader is not the same as or an ancestor of the class loader for the class whose class loader is requested, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the class loader for the class.

getClassLoader() 什么时候抛出 SecurityException?我认为调用者的类加载器始终与请求类加载器的类的类加载器相同。

最佳答案

I would think the caller's class loader is always the same as the class loader for the class whose class loader is requested.

你的想法是错误的。

假设您的类是不受信任的代码,已使用沙箱类加载器加载到安全沙箱中。并且您的类正在(比如说)已由默认类加载器加载的系统类上调用 getClassLoader()

在这种情况下,类加载器会有所不同,并且会有一个安全管理器,因此将调用 checkPermission 来检查是否允许(不受信任的)代码获取类加载器。如果不允许,则会抛出 SecurityException

<小时/>

注意:“调用者的类加载器”是指加载进行调用的类的类加载器。

例如,在这段代码中:

public class Foo {
public void method(Bar bar) {
bar.getClass().getClassLoader()
}
}

“调用者”是方法,而 getClassLoader() 调用的“调用者的类加载器”是 Foo 的类加载器类(class)。将对其进行测试,看看它是否是 Bar 类的同一个类加载器。 (或更准确地说,是 getClass() 调用返回的类。)

关于java - Class 的 getClassLoader() 什么时候抛出 SecurityException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50017522/

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