Get JAR file version number

I have an application used in clustering so that it is available if one or more failures, and I want to implement a way to check jar file version in java.

I have this piece of code for this (for example: in the MyClass class):

        URLClassLoader cl = (URLClassLoader) (new MyClass ())
            .getClass().getClassLoader();
        URL url = cl.findResource("META-INF/MANIFEST.MF");
        Manifest manifest = new Manifest(url.openStream());
        attributes = manifest.getMainAttributes();
        String version = attributes.getValue("Implementation-Version");

When I run jar as an application, it works fine, but when I use the jar file as librairie in another application, I get the version number of another application.

So my question is: how can I get the jar manifest where MyClass is contained?

NB: I am not interested in a solution using static constraints such as 'classLoader.getRessource ("MyJar.jar")' or a file ("MyJar.jar")

+4
4

, :

    // Get jarfile url
    String jarUrl = JarVersion.class
        .getProtectionDomain().getCodeSource()
        .getLocation().getFile();

    JarFile jar = new JarFile(new File(jarUrl));
    Manifest manifest = jar.getManifest();
    Attributes attributes = manifest.getMainAttributes();

    String version = attributes.getValue(IMPLEMENTATION_VERSION) 
0

- Package.getImplementationVersion():

String version = MyClass.class.getPackage().getImplementationVersion();
+4

:

java.io.File file = new java.io.File("/packages/file.jar"); //give path and file name
java.util.jar.JarFile jar = new java.util.jar.JarFile(file);
java.util.jar.Manifest manifest = jar.getManifest();

String versionNumber = "";
java.util.jar.Attributes attributes = manifest.getMainAttributes();
if (attributes!=null){
    java.util.Iterator it = attributes.keySet().iterator();
    while (it.hasNext()){
        java.util.jar.Attributes.Name key = (java.util.jar.Attributes.Name) it.next();
        String keyword = key.toString();
        if (keyword.equals("Implementation-Version") || keyword.equals("Bundle-Version")){
            versionNumber = (String) attributes.get(key);
            break;
        }
    }
}
jar.close();

System.out.println("Version: " + versionNumber); //"here it will print the version"

, . .

+2

Source: https://habr.com/ru/post/1545228/


All Articles