小编典典

java如何在运行时动态加载JAR文件?

java jar

为什么用Java这么难?如果要使用任何类型的模块系统,则需要能够动态加载JAR文件。有人告诉我,有一种方法可以通过编写自己的方法来完成ClassLoader,但这对于(至少在我看来)应该像调用以JAR文件作为其参数的方法那样容易的事情来说是很多工作。


阅读 1727

收藏
2020-01-10

共1个答案

小编典典

很难的原因是安全性。类加载器是不可变的。您不应在运行时随意向其添加类。实际上,我很惊讶能与系统类加载器一起使用。这是制作自己的子类加载器的方法:

URLClassLoader child = new URLClassLoader(
        new URL[] {myJar.toURI().toURL()},
        this.getClass().getClassLoader()
);
Class classToLoad = Class.forName("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod("myMethod");
Object instance = classToLoad.newInstance();
Object result = method.invoke(instance);

以下解决方案有些骇人,因为它使用反射来绕过封装,但是可以完美地工作:

File file = ...
URL url = file.toURI().toURL();

URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(classLoader, url);
2020-01-10