URLClassLoader为某些条目抛出ClassNotFoundException

时间:2018-05-29 14:09:59

标签: java exception urlclassloader

我正在编写一段代码,它使用Java版本v8 u112上的URLClassLoader从JAR文件加载java类

我正在使用下面的摘录:

// Create URlClassLoader
Path jarFilePath = Paths.get(...);
URLClassLoader loader = URLClassLoader.newInstance(new URL[] { jarFilePath .toUri().toURL() }, ClassLoader.getSystemClassLoader());

// Filter only .class entries from JAR file since JAR contains *.xml, *.txt etc.
JarFile jarFile = new JarFile(path.toAbsolutePath().toFile()));
List<String> javaClasses = filterJavaClasses(jarFile); // filters only entries with .class extension.

// Attempt class loading. I used the help of BCEL since it converts class to JavaClass which is easier to work with. 
javaClasses.map(clazz -> Repository.lookupClass(loader.loadClass(clazz)))...

Note, the same issue happens even if I don't use BCEL...

在加载JAR文件时,大多数类都加载没有问题,但在加载某些特定类时遇到问题,即com / sun / javadoc / Doclet,com / sun / tools / javadoc / Messager,org / apache / sshd / server / SshServer等。

有没有人在使用URLClassLoader时遇到过这样的问题?

以下的例外情况

java.lang.NoClassDefFoundError: com/sun/javadoc/Doclet
    at java.lang.ClassLoader.defineClass1(Native Method) ~[?:1.8.0_112]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[?:1.8.0_112]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[?:1.8.0_112]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[?:1.8.0_112]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[?:1.8.0_112]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[?:1.8.0_112]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[?:1.8.0_112]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_112]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[?:1.8.0_112]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_112]
    at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:814) ~[?:1.8.0_112]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_112]

1 个答案:

答案 0 :(得分:0)

您不仅需要将您的罐子放在网址列表中,还要将这些罐子所依赖的罐子和它们的依赖关系......

例如com / sun / javadoc / Doclet是JAVA_HOME / lib / tools.jar的一部分,默认情况下不会被systemclassloader加载,除非你专门将tools.jar添加到类路径中。