Search code examples
javaclassloader

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


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.


Solution

  • 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.