简体   繁体   中英

URLClassloader Dependencies

In my previous question, I asked how to load remote jar files. My current code is this:

//f is the path to the jar
URLClassLoader loader = new URLClassLoader(new URL[]{f.toURI().toURL()});
Class<?> jarClass = Class.forName(main, true, loader);
Class<? extends Module> module = jarClass.asSubclass(Module.class);

Constructor<? extends Module> constructor = module.getConstructor();
System.out.println(constructor);

Module module = constructor.newInstance();

This works well, but the remotely-loaded modules extend a class that is in the jar that is loading them, which gives this error:

Caused by: java.lang.ClassNotFoundException: package.whatever.Module, which I presume is because it is using URLClassLoader instead of getClass().getClassLoader().. how can I make it use URLClassLoader and then fall back to the default one?

Thanks,
Bart

You can set your application class loader to be the parent of the url class loader:

URLClassLoader loader = new URLClassLoader(
       new URL[]{f.toURI().toURL()}, Module.class.getClassLoader());

From the Oracle Java tutorial (class loading mechanism):

The Java platform uses a delegation model for loading classes. The basic idea is that every class loader has a "parent" class loader. When loading a class, a class loader first "delegates" the search for the class to its parent class loader before attempting to find the class itself.

我遇到了同样的问题而我正在使用Java 9,将其降级为Java 8解决了我的问题。

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