我当前的Java项目正在使用另一个项目(相同的程序包)中的方法和变量。现在,另一个项目的jar必须位于类路径中才能正常工作。我的问题是,jar的名称可能会并且将由于版本的增加而更改,并且因为您不能在清单类路径中使用通配符,所以无法将其添加到类路径中。因此,当前启动我的应用程序的唯一选择是从命令行使用-cp
参数,手动添加项目所依赖的另一个jar。
为了改善这一点,我想动态地加载jar并阅读有关使用ClassLoader的信息。我阅读了很多示例,但是仍然不了解如何使用。
我想要的是加载一个jar文件,比方说myDependency-2.4.1-SNAPSHOT.jar
,但是它应该能够搜索以myDependency-
开头的jar文件,因为正如我已经说过的那样,版本号可以随时更改。然后,我应该能够像现在一样在代码中使用它的方法和变量(例如ClassInMyDependency.exampleMethod()
)。
任何人都可以帮我解决这个问题,因为我已经在网上搜索了几个小时,但是仍然不知道如何使用ClassLoader来完成我刚刚解释的事情。
非常感谢
实际上,这有时是必要的。这就是我在生产中执行此操作的方式。它使用反射来规避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);
}
}
我需要在运行时为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());
}
}