简体   繁体   中英

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. If I do it yields a 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.

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?

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.

Main Class Loader -> ChildFirstClassLoader -> Loads jar and dependent jars

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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