【发布时间】:2018-03-14 18:36:18
【问题描述】:
使用的技术: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
【问题讨论】:
-
你有什么问题?
-
@PaL
I have a module (A) that is referencing another module (B) and I would like to get B's module version at runtime.