Get jar version in runtime

Be careful using getPackage().getImplementationVersion/getSpecificationVersion()

getSpecificationVersion returns specVersion from Manifest. Manifest is a property of a jar and is used in sun.misc.URLClassPath as

  public Manifest getManifest() throws IOException {
                    SharedSecrets.javaUtilJarAccess().ensureInitialization(JarLoader.this.jar);
                    return JarLoader.this.jar.getManifest();
                }

So in case somebody use your library as dependency for fat jar, it returns the version of Manifest for fat jar.


Try this, it may be helpful:

String s = new String();
System.out.println(s.getClass().getPackage().getSpecificationVersion());
System.out.println(s.getClass().getPackage().getImplementationVersion());

Output:

1.7
1.7.0_25

import javax.mail.internet.InternetAddress;

/**
Display package name and version information for javax.mail.internet.
*/
public final class ReadVersion {
  public static void main(String... aArgs){
    ReadVersion readVersion = new ReadVersion();
    readVersion.readVersionInfoInManifest();
  }

  public void readVersionInfoInManifest(){
    InternetAddress object = new InternetAddress();
    Package objPackage = object.getClass().getPackage();
    //examine the package object 
    String name = objPackage.getSpecificationTitle();
    String version = objPackage.getSpecificationVersion();
    //some jars may use 'Implementation Version' entries in the manifest instead
    System.out.println("Package name: " + name);
    System.out.println("Package version: " + version);
  }
}