简体   繁体   English

加载具有外部依赖关系的外部类-URLClassLoader ClassNotFoundException

[英]Loading external Classes with external dependencies - URLClassLoader ClassNotFoundException

I am loading a Class from an external.JAR file and by means of URLClassLoader, which works as long as the external Class does not reference another JAR. 我正在通过external.JAR文件并通过URLClassLoader加载类,只要外部类不引用另一个JAR,该类就可以工作。 If I do it yields a ClassNotFoundException. 如果我这样做,将产生ClassNotFoundException。

As a workaround I add the other second tier JAR as a dependency, but I would like to load these also dynamically on runtime. 作为解决方法,我将其他第二层JAR添加为依赖项,但我想在运行时动态加载它们。

Question: How do I load an external Class which references other external classes? 问题:如何加载引用其他外部类的外部类? or how do I load external JAR files and classes, in the correct order so I am not getting an exception? 或如何以正确的顺序加载外部JAR文件和类,以免出现异常?

Should I catch the exception and then "first" load that class that was not yet loaded? 我应该捕获异常,然后“首先”加载尚未加载的类吗?

You actually could load them all using a child first class loader. 您实际上可以使用子一流的加载器加载它们。 That main jar and all of its dependencies would be apart of that class loader and can be referenced and thrown away if needed. 该主jar及其所有依赖项将属于该类加载器,并且可以在需要时被引用和丢弃。

Main Class Loader -> ChildFirstClassLoader -> Loads jar and dependent jars 主类加载器-> ChildFirstClassLoader->加载jar和从属jar

This is a good example 这是一个很好的例子

Here is another SO similar reference 这是另一个类似的参考

Semi Example 半示例

File file = new File("c:\\free-universe-games-llc\\app.jar");
URL url = file.toURI().toURL();
ChildFirstClassLoader urlClassLoader = new ChildFirstClassLoader(new URL[]{url}, SomeClassLoader.class.getClassLoader()); 
Class<?> aClass = urlClassLoader.loadClass("com.freeuniversegames.app.App.class");
Object o = aClass.newInstance();

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

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