简体   繁体   English

动态加载类文件时抛出ClassNotFoundException

[英]ClassNotFoundException Thrown when Dynamically Loading Class Files

We have a servlet project, which contains (among many other classes) an interface that we expose to users. 我们有一个servlet项目,它包含(在许多其他类中)我们向用户公开的接口。

Users can compile their own classes (in the form of .class files) that implement the provided interface, and place them in a folder that our project is aware of. 用户可以编译自己的类(以.class文件的形式)来实现提供的接口,并将它们放在我们项目知道的文件夹中。 When the servlet starts, it uses a URLClassLoader to load all the .class files in that folder. 当servlet启动时,它使用URLClassLoader加载该文件夹中的所有.class文件。 (So users can hook in to certain events.) (因此用户可以参与某些活动。)

As far as I can tell, the class file is located and loaded properly, kind of. 据我所知,类文件的位置和加载正确, 类型。 When loading the user's compiled .class file, a ClassNotFoundException exception is thrown, but it's complaining about the interface, which should already be on the classpath. 在加载用户编译的.class文件时,会抛出ClassNotFoundException异常,但是它会抱怨接口,该接口应该已经在类路径中。

Caused by: java.lang.ClassNotFoundException: com.company.project.OurInterface
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)

When dynamically loading the .class file, is there a reason the interface is not found? 动态加载.class文件时,是否有找不到接口的原因?

Perhaps you haven't specified parent classloader for your URLClassLoader . 也许您没有为URLClassLoader指定父类加载器。

Your application's classloader should be a parent classloader of your dynamic classloader: 您的应用程序的类加载器应该是动态类加载器的父类加载器:

ClassLoader dynamicClassLoader = 
    new URLClassLoader(..., OutInterface.class.getClassLoader());

Maybe it's because you try to load that interface from the "dynamic classes"-path? 也许是因为你试图从“动态类”-path加载该接口? What happens when you drop your interface in there, too? 当你将界面放在那里时会发生什么?

Probably because you're using a different class loader, and it's not finding the classes loaded by it's classloader. 可能是因为你正在使用不同的类加载器,而且它没有找到由它的类加载器加载的类。

Have you considered using a SPI for this instead? 您是否考虑过使用SPI代替? http://download.oracle.com/javase/1.4.2/docs/guide/jar/jar.html#Service%20Provider (sorry for the old link, but the approach is the same. http://download.oracle.com/javase/1.4.2/docs/guide/jar/jar.html#Service%20Provider (对不起旧的链接,但方法是一样的。

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

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