正在使用的技术:Java 1.8和Maven
我有一个模块(A)引用另一个模块(B),我希望在运行时获得B的模块版本。
下面的代码是在运行时返回A的版本而不是B的版本。
我也引用了另一个问题: reading MANIFEST.MF file from jar file using JAVA
模块(B)中返回其版本的代码:
public static String getVersion() {
if (StringUtils.isBlank(version)) {
Class<?> clazz = Runner.class;
String className = clazz.getSimpleName() + ".class";
String classPath = clazz.getResource(className).toString();
if (!classPath.startsWith("jar")) {
// Class not from JAR
String relativePath = clazz.getName().replace('.', File.separatorChar) + ".class";
String classFolder = classPath.substring(0, classPath.length() - relativePath.length() - 1);
String manifestPath = classFolder + "/META-INF/MANIFEST.MF";
//log.debug("manifestPath={}", manifestPath);
version = readVersionFrom(manifestPath);
} else {
String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
System.out.println(String.format("manifestPath={%s}", manifestPath));
version = readVersionFrom(manifestPath);
}
}
return version;
}
private static String readVersionFrom(String manifestPath) {
Manifest manifest = null;
try {
manifest = new Manifest(new URL(manifestPath).openStream());
Attributes attrs = manifest.getMainAttributes();
String implementationVersion = attrs.getValue("Implementation-Version");
implementationVersion = StringUtils.replace(implementationVersion, "-SNAPSHOT", "");
//log.debug("Read Implementation-Version: {}", implementationVersion);
String implementationBuild = attrs.getValue("Implementation-Build");
//log.debug("Read Implementation-Build: {}", implementationBuild);
String version = implementationVersion;
if (StringUtils.isNotBlank(implementationBuild)) {
version = StringUtils.join(new String[] { implementationVersion, implementationBuild }, '.');
}
return version;
} catch (Exception e) {
//log.error(e.getMessage(), e);
}
return StringUtils.EMPTY;
}
模块(A)中的代码从模块(B)获取版本:
moduleB.getVersion()
命令我用来运行模块(A)打包的jar:
java -jar test.jar
答案 0 :(得分:0)
public static Manifest manifest(Class<?> clazz) throws IOException {
URL resource = clazz.getResource("/" + clazz.getName().replace(".", "/") + ".class");
System.out.println(resource);
String resourceBase = resource.toString().replace(clazz.getName().replace(".", "/") + ".class", "");
System.out.println(resourceBase);
Enumeration<URL> resources = clazz.getClassLoader().getResources("META-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
try {
URL nextElement = resources.nextElement();
if (nextElement.toString().equals(resourceBase + "META-INF/MANIFEST.MF")) {
System.out.println(nextElement);
Manifest manifest = new Manifest(nextElement.openStream());
return manifest;
}
} catch (IOException E) {
//
}
}
return null;
}
的System.out.println(清单(T.class).getMainAttributes()的getValue(&#34;实施-版&#34));
不要忘记检查是否有清单,它会返回null