Why can I not look up classes from sun.misc.DelegatingClassLoader

风流意气都作罢 提交于 2019-12-11 12:50:26

问题


From this question, I found that it is not possible to look up a class from a sun.misc.DelegatingClassLoader, i.e. looking up a class on its own class loader like

Class<?> accessor = ...
accessor.getClassLoader().findClass(accessor.getName());

throws a ClassNotFoundException. The delegating class loader is used for loading runtime-generated accessor classes for converting Java's reflective JNI calls into Java invocations.

For some strange reason, I am not able to find the source of the DelegatingClassLoader anywhere in the JDK sources even though it is clearly available in my build where it seems to be an empty implementation of a subclass of the standard ClassLoader from looking at the class's byte code.

If the DelegatingClassLoader is however really only a simple subclass, I do not understand why it is not possible to look up a class by its name. Is there some VM magic involved? It seems like the

private native final Class<?> findLoadedClass0(String name);

method does not return the loaded class for a DelegatingClassLoader. The private classes field does however include the loaded class.

I was not able to find any information on how these class loaders are supposed to be different from any other class loaders. I am looking for an explanation why the above lookup does not work but throws an exception.


回答1:


The source for DelegatingClassLoader is for whatever reason located in ClassDefiner.java. Interestingly, this code has a comment that references bug 4474172, which suggests that this class loader is known to the JVM and has special behavior:

The second solution is to make the virtual machine "magically" delegate class loading for these newly-fabricated class loaders to their parent loaders, without making an upcall to Java. The disadvantage is that this is another hack in the JVM [...]. This option has been chosen.



来源:https://stackoverflow.com/questions/29094310/why-can-i-not-look-up-classes-from-sun-misc-delegatingclassloader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!