我当前的java项目正在使用来自另一个项目(相同的包)的方法和变量。现在,另一个项目的jar必须在类路径中才能正常工作。我这里的问题是,jar的名称可能会因版本增加而更改,而且因为不能在清单类路径中使用通配符,所以不可能将其添加到类路径中。因此,目前启动应用程序的惟一选择是从命令行使用-cp参数,手动添加我的项目所依赖的另一个jar。
为了改进这一点,我想动态加载jar并阅读有关使用ClassLoader的内容。我读了很多关于它的例子,但是我仍然不明白如何在我的例子中使用它。
我想要的是加载一个jar文件,比如说myDependency-2.4.1-SNAPSHOT.jar,但是它应该能够只搜索以myDependency-开头的jar文件,因为正如我已经说过的,版本号可以随时更改。然后,我应该能够像现在一样在我的代码中使用它的方法和变量(如ClassInMyDependency.exampleMethod())。
有人能帮我解决这个问题吗?我已经在网上搜索了几个小时了,但仍然不知道如何使用ClassLoader来做我刚才解释的事情。
非常感谢你提前
发布于 2014-11-28 19:25:10
(适用于Java版本8及更早版本)。
事实上,这有时是必要的。这就是我在生产中的方法。它使用反射来绕过系统类加载器中的addURL封装。
/*
* Adds the supplied Java Archive library to java.class.path. This is benign
* if the library is already loaded.
*/
public static synchronized void loadLibrary(java.io.File jar) throws MyException
{
try {
/*We are using reflection here to circumvent encapsulation; addURL is not public*/
java.net.URLClassLoader loader = (java.net.URLClassLoader)ClassLoader.getSystemClassLoader();
java.net.URL url = jar.toURI().toURL();
/*Disallow if already loaded*/
for (java.net.URL it : java.util.Arrays.asList(loader.getURLs())){
if (it.equals(url)){
return;
}
}
java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});
method.setAccessible(true); /*promote the method to public access*/
method.invoke(loader, new Object[]{url});
} catch (final java.lang.NoSuchMethodException |
java.lang.IllegalAccessException |
java.net.MalformedURLException |
java.lang.reflect.InvocationTargetException e){
throw new MyException(e);
}
}发布于 2020-02-18 20:54:13
我需要在运行时为java 8和java 9+加载一个jar文件。下面是实现这一点的方法(如果可能的话,使用Spring Boot 1.5.2 )。
public static synchronized void loadLibrary(java.io.File jar) {
try {
java.net.URL url = jar.toURI().toURL();
java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});
method.setAccessible(true); /*promote the method to public access*/
method.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{url});
} catch (Exception ex) {
throw new RuntimeException("Cannot load library from jar file '" + jar.getAbsolutePath() + "'. Reason: " + ex.getMessage());
}
}https://stackoverflow.com/questions/27187566
复制相似问题