Add version to Jar packagingTag(s): Environment


Let's say we have the following class (package is mandatory)
package com.rgagnon;

public class Hello {
 public static void main(String[] args) {
    new Hello().say("Hello World!");
 }

 public void say(String s) {
    System.out.println(s);
 }
}
First create a MANIFEST.MF file :
Manifest-Version: 1.0
Main-Class: com.rgagnon.Hello
Then build the executable Jar and run it.
>jar cvfm hello.jar MANIFEST.MF com\rgagnon\Hello.class

>java -jar hello.jar
Hello World!
Now modify the manifest to include versioning information.
Manifest-Version: 1.0
Main-Class: com.rgagnon.Hello
Specification-Version: 2.1
Implementation-Version: 1.1
Modify the class to display the version.
package com.rgagnon;

public class Hello {
 public static void main(String[] args) {
    new Hello().say("Hello World!");
 }

 Hello() {
   Package p = this.getClass().getPackage();
   System.out.println("Hello Specification Version : "
                         + p.getSpecificationVersion());
   System.out.println("Hello Implementation Version : "
                         + p.getImplementationVersion());
 }

 public void say(String s) {
    System.out.println(s);
 }
}
Compile and rebuild the Jar and execute
> jar cvfm hello.jar MANIFEST.MF com\rgagnon\Hello.class

> java -jar hello.jar
Specification Version : 2.1
Implementation Version : 1.1
Hello World!

See also this Howto.

This example opens a given Jar and outputs its version information.

package com.rgagnon.howto;

import java.util.jar.*;

public class JarUtils {

  private JarUtils() {}

  public static String getJarImplementationVersion(String jar)
       throws java.io.IOException
  {
    JarFile jarfile = new JarFile(jar);
    Manifest manifest = jarfile.getManifest();
    Attributes att = manifest.getMainAttributes();
    return att.getValue("Implementation-Version");
  }

  public static String getJarSpecificationVersion(String jar)
       throws java.io.IOException
  {
    JarFile jarfile = new JarFile(jar);
    Manifest manifest = jarfile.getManifest();
    Attributes att = manifest.getMainAttributes();
    return att.getValue("Specification-Version");
  }
  public static void main(String[] args) throws java.io.IOException{
    String javaMailJar = "C:/Program Files/Java/jre1.5.0/lib/mail.jar";

    System.out.println("Specification-Version: "
        + JarUtils.getJarSpecificationVersion(javaMailJar));
    System.out.println("Implementation-Version: "
        + JarUtils.getJarImplementationVersion(javaMailJar));
    /*
     * output :
     *      Specification-Version: 1.3
     *      Implementation-Version: 1.3.1
     */
  }
}

blog comments powered by Disqus