From this question ,我发现不可能从 sun.misc.DelegatingClassLoader
查找类,即在其自己的类加载器上查找类,例如
Class<?> accessor = ...
accessor.getClassLoader().findClass(accessor.getName());
抛出ClassNotFoundException
。委托(delegate)类加载器用于加载运行时生成的访问器类,以将 Java 的反射 JNI 调用转换为 Java 调用。
出于某种奇怪的原因,我是not able to find the source of the DelegatingClassLoader
anywhere in the JDK sources尽管它在我的构建中显然可用,但从类的字节代码来看,它似乎是标准 ClassLoader
子类的空实现。
如果DelegatingClassLoader
实际上只是一个简单的子类,我不明白为什么不能通过名称查找类。是否涉及一些虚拟机魔法?好像是这样的
private native final Class<?> findLoadedClass0(String name);
方法不会返回 DelegatingClassLoader
加载的类。然而,私有(private)classes
字段确实包含加载的类。
我无法找到有关这些类加载器与任何其他类加载器有何不同的任何信息。我正在寻找解释为什么上述查找不起作用但抛出异常。
最佳答案
DelegatingClassLoader 的源出于某种原因位于 ClassDefiner.java 。有趣的是,这段代码有一个引用 bug 4474172 的注释。 ,这表明 JVM 已知该类加载器并且具有特殊行为:
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.
关于java - 为什么我无法从 sun.misc.DelegatingClassLoader 查找类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29094310/