java - 从jar调用main jar

时间:2016-10-25 14:28:17

标签: java

我正在尝试调用一个打包在jar(B.jar)中的主类。我从java代码调用它。这在我从IDE运行时有效。但是当我将我的代码打包到jar(A.jar)中,然后从命令行调用我的代码时,我得到异常" java.lang.NullPointerException:no!/ in spec"。以下是我如何从A.jar调用B.jar的代码片段。

URL resource = getClass().getResource(B.jar);
URL[] urls = {resource.toURI().toURL()};
URLClassLoader loader = new URLClassLoader(urls);
URL url =  new URL("jar", "", resource + "!/");
JarURLConnection uc = (JarURLConnection) url.openConnection();
// this is where excption is being thrown - "java.lang.NullPointerException: no !/ in spec".
Attributes attr = uc.getMainAttributes();
String mainClass = attr.getValue(Attributes.Name.MAIN_CLASS);
Class<?> cls = loader.loadClass(mainClass);
Method mainMethod = cls.getDeclaredMethod("main", String[].class);
Object response = mainMethod.invoke(null, new Object[]{args});

0 个答案:

没有答案