Java 9:如何动态地将更多jar文件添加到classpath [英] Java 9: how to add further jar files to classpath dynamically

查看:737
本文介绍了Java 9:如何动态地将更多jar文件添加到classpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们基于Java的应用程序有一个很小的bootloader.jar和核心应用程序jar。核心应用程序jar可以从默认(文件系统)位置加载,也可以从上次运行的应用程序可能已下载更新的jar的其他位置加载。引导程序运行以下代码:

Our Java-based application has a tiny "bootloader.jar" and the core application jars. The core application jars might be loaded either from the default (file system) location or from another where a previous application run might have downloaded updated jars. The bootloader runs following code:

final List<File> jars = getJarsToAddToClasspath();
final String mainClassName = getMainClassName();

final URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());
final Class<?> mainClass = urlClassLoader.loadClass(mainClassName);
final Method mainMethod = mainClass.getDeclaredMethod("main", String[].class);
mainMethod.invoke(null, new Object[] {args});

根据 http://www.oracle.com/technetwork/java/javase/9​​-relnote-issues-3704069.html 它看起来这样就不再适用于Java 9:

According to http://www.oracle.com/technetwork/java/javase/9-relnote-issues-3704069.html it looks like this won't work any more with Java 9:


请注意,Java SE和JDK不为应用程序或$提供API b $ b库在运行时动态增加类路径。

Note that Java SE and the JDK do not provide an API for applications or libraries to dynamically augment the class path at run-time.

有人可以确认吗?

推荐答案

我认为它应该仍然有效。最简单的方法就是尝试一下。来自同一Oracle页面:

I think it should still work. The simplest way to know is to try it. From the same Oracle page:


假设 ClassLoader :: getSytemClassLoader 返回的代码需要更新 URLClassLoader 对象。

Code that assumes that ClassLoader::getSytemClassLoader returns a URLClassLoader object will need to be updated.

您的代码不依赖系统类加载器的类型为 URLClassloader 。它所做的就是将其设置为自定义类加载器的委托父级。这个自定义类加载器将委托它来搜索类和资源,无论其实现如何。

Your code does not rely on the system classloader being of type URLClassloader. All it does is set it as the delegated parent of the custom classloader. This custom classloader will delegate to it to search for classes and resources regardless of its implementation.

这篇关于Java 9:如何动态地将更多jar文件添加到classpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆