问题出在这一行代码上:

addURLMethod.invoke(classLoader, new URL("jar:" + jarFileUrl + "!/META-INF/MANIFEST.MF"));

在加载Jar文件时,你只需要将Jar文件的URL地址添加到classLoader中即可,不需要加上"jar:"和"!/META-INF/MANIFEST.MF"。

修改后的代码如下:

@GetMapping(value = "/JarLauncherJar") //运行JarLauncher的jar包 public String JarLauncherJar() throws MalformedURLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {

// 创建 URLClassLoader,并将当前 JAR 文件添加到类路径中
URL jarFileUrl = new URL("file:E:/jetlinks/jar/gt06-gsp-java-1.0.1.jar");
URLClassLoader classLoader = new URLClassLoader(new URL[]{jarFileUrl});
Method addURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
addURLMethod.setAccessible(true);
addURLMethod.invoke(classLoader, jarFileUrl);
// 加载 JarLauncher 和 Launcher 类
Class<?> jarLauncherClass = classLoader.loadClass("org.springframework.boot.loader.JarLauncher");
Class<?> launcherClass = classLoader.loadClass("org.springframework.boot.loader.Launcher");

// 获取 Launcher 类中 launch 方法
Method launchMethod = launcherClass.getDeclaredMethod("launch", String[].class);
String[] mainArgs = { "arg1", "arg2" };  // 根据需要提供命令行参数
launchMethod.setAccessible(true);
// 调用 launch 方法启动 JAR 文件
launchMethod.invoke(jarLauncherClass.getDeclaredConstructor().newInstance(), (Object) mainArgs);
//launchMethod.invoke(jarLauncherClass.getDeclaredConstructor().newInstance(), new Object[]{mainArgs});
return null;
GetMappingvalue = JarLauncherJar 运行JarLauncher的jar包 public String JarLauncherJar throws MalformedURLException ClassNotFoundException NoSuchMethodException InvocationTargetException InstantiationExc

原文地址: https://www.cveoy.top/t/topic/hHIO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录