zibi zibi - 5 months ago 67
Java Question

Get jar version in runtime

I'm wondering if it is possible to retrieve, in runtime, a version number of a jar from which the class comes from?

I know its possible to find jar from which the class comes from:

MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();


but what about a version?

(assuming its not in the file name:) )

Answer
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);
  }
}