[英]Describe MANIFEST.MF with classpath like java -cp
I have a command line Java application, which has dependencies to other libs/jars. 我有一个命令行Java应用程序,它与其他libs / jar有依赖关系。 Therefore I'm running the application with the -cp
, eg java -cp libs/* <package.MainClass> <args>
. 因此我使用-cp
运行应用程序,例如java -cp libs/* <package.MainClass> <args>
。
What I'm trying to do is to copy the dependency libs/jars in my Java application and describing correctly the MANIFEST.MF with the reason that I don't need the option -cp libs/*
anymore. 我想要做的是复制我的Java应用程序中的依赖libs / jars并正确描述MANIFEST.MF,原因是我不再需要-cp libs/*
选项。
My project is a maven project, therefore I'm using the maven-assembly-plugin
to copy the libs in my JAR and describing the MANIFEST.MF. 我的项目是一个maven项目,因此我使用maven-assembly-plugin
来复制我的JAR中的lib并描述MANIFEST.MF。 What I'm right now is the following: 我现在的情况如下:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<archive>
<manifest>
<mainClass>MainClass</mainClass>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>dist</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
And my MANIFEST.MF looks like this atm: 我的MANIFEST.MF看起来像这个atm:
Manifest-Version: 1.0
Built-By: user
Class-Path: lib/deps_A.jar lib/deps_B.jar
Created-By: Apache Maven 3.6.0
Build-Jdk: 1.8.0_202
Main-Class: MainClass
My Question is: How can describe the MANIFEST.MF file, so that I run my application with java -jar <my-jar-application.jar> <args>
? 我的问题是:如何描述MANIFEST.MF文件,以便用java -jar <my-jar-application.jar> <args>
运行我的应用java -jar <my-jar-application.jar> <args>
?
The manifest entries are not listed among the URLs of the SystemClassLoader . 清单条目未列在SystemClassLoader的URL中。
You have to manually get them from the manifest file. 您必须从清单文件中手动获取它们。
ClassLoader cl = ClassLoader.getSystemClassLoader();
if (cl instanceof URLClassLoader) {
URLClassLoader ucl = (URLClassLoader) cl;
URL[] urLs = ucl.getURLs();
for (URL url : urLs) {
File file = new File(URLDecoder.decode(url.getFile()));
try (JarFile jarFile = new JarFile(file)){
Manifest manifest = jarFile.getManifest();
String attrs = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH.toString());
if(attrs!=null) {
String[] splits = attrs.split(" ");
for (String split: splits) {
// This is the name of the jar referenced in manifest.
System.out.println(split);
}
}
System.out.println(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I took inspiration from guava lib, you can also check the sources of Classpath class. 我从guava lib中获取灵感,你也可以检查Classpath类的来源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.