Using the method found in second answer here:
reading MANIFEST.MF file from jar file using JAVA
and adding a conditional in the Attributes
- checking on the title as presented in MANIFEST.MF returns the proper version.
public static String getManifestInfo() {
Enumeration resEnum;
try {
resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
while (resEnum.hasMoreElements()) {
try {
URL url = (URL)resEnum.nextElement();
InputStream is = url.openStream();
if (is != null ) {
Manifest manifest = new Manifest(is);
Attributes mainAttribs = manifest.getMainAttributes();
String version = mainAttribs.getValue("Implementation-Version");
String name = mainAttribs.getValue("Implementation-Title");
if (version != null && name != null) {
if ("packagetitle".equals(name))
return version;
}
}
}
catch (Exception e) {
// Silently ignore wrong manifests on classpath?
}
}
} catch (IOException e1) {
// Silently ignore wrong manifests on classpath?
}
return null;
}
This can surely be made even more effectively by skipping the iteration using stream() if knowing details about the package itself, but at least this works as intended.