简体   繁体   English

URLClassloader依赖项

[英]URLClassloader Dependencies

In my previous question, I asked how to load remote jar files. 在我之前的问题中,我询问了如何加载远程jar文件。 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: 这很好用,但远程加载的模块扩展了一个加载它们的jar中的类,这会产生以下错误:

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? 引起:java.lang.ClassNotFoundException:package.whatever.Module,我认为是因为它使用的是URLClassLoader而不是getClass()。getClassLoader()..如何使用URLClassLoader然后回退到默认值?

Thanks, 谢谢,
Bart 巴特

You can set your application class loader to be the parent of the url class loader: 您可以将应用程序类加载器设置为url类加载器的父级:

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

From the Oracle Java tutorial (class loading mechanism): Oracle Java教程 (类加载机制):

The Java platform uses a delegation model for loading classes. Java平台使用委托模型来加载类。 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解决了我的问题。

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

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