简体   繁体   English

java:类加载器

[英]java : ClassLoaders

Say, I have a class A, loaded by ClassLoader CL1. 说,我有一个由ClassLoader CL1加载的A类。

I have another class B, loaded by ClassLoader CL2. 我还有另一个Class B,由ClassLoader CL2加载。

Assume both classes are now loaded by their respective ClassLoaders. 假设两个类现在都由各自的ClassLoader加载。

From A, if I execute the following statement, what would be the result : B.class.getClassLoader(); 从A,如果我执行以下语句,将得到什么结果:B.class.getClassLoader();

Will it return CL2? 它会返回CL2吗? Please clarify. 请澄清。

Thanks HV 谢谢HV

Will it return CL2? 它会返回CL2吗?

In the case where it has permission to do so then yes - why wouldn't it? 如果它有权这样做,那就可以-为什么不呢? The result has no bearing on what class you execute the method from , it is to do with what class you execute the method on (which in this case, is B.class which was loaded by CL2.) 结果有 ,这是你执行的方法是什么类做你执行方法是什么类没有关系(在这种情况下,是B.class这是由CL2加载。)

From the docs : 文档

Returns the class loader for the class. 返回该类的类加载器。 Some implementations may use null to represent the bootstrap class loader. 一些实现可能使用null来表示引导类加载器。 This method will return null in such implementations if this class was loaded by the bootstrap class loader. 如果此类是由bootstrap类加载器加载的,则此方法在此类实现中将返回null。

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. 如果存在安全管理器,并且调用方的类加载器不为null且调用方的类加载器与请求其类加载器的类的祖先或类加载器的祖先不同,则此方法调用安全管理器的checkPermission方法具有RuntimePermission(“ getClassLoader”)权限,以确保可以访问该类的类加载器。

So assuming it's an actual class that you've loaded (rather than a primitive), and the security manager says that you have permission to check the class, yes - it will return the corresponding classloader (CL2 in this instance.) 因此,假设这是您已加载的实际类(而不是原始类),并且安全管理器说您有权检查该类,是的-它会返回相应的类加载器(在此实例中为CL2)。

It does return the classloader which loaded class B but caller should have permission on that class loader. 它确实返回加载了类B的类加载器,但调用者应具有该类加载器的权限。

Check the API doc 检查API文档

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getClassLoader() http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getClassLoader()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM