Read jar version information

A jar file is simply a zipped (compressed) collection of class files, and any associated resources.

It's often important to know which version of a jar file is being used by an application. For example, upon startup, an application might find it useful to log the version numbers of all of its known jars. This can be very useful for debugging problems later on.

The MANIFEST file is a text file included with each jar, which specifies high-level information about its contents. The MANIFEST file usually includes version information. That version information is, in turn, accessible at run time using methods of the Package class.

Example

The following example extracts the name and version of the package containing the class InternetAddress. (If the javax.mail.internet package is not on your class path, you can easily modify this code to examine some other package.)

import javax.mail.internet.InternetAddress;

/**
 Display package name and version information for 
 javax.mail.internet.

 As long as you can build on object of some known class,
 you may get its related package info in this way.
*/
public final class ReadVersion {
  
  public static void main(String... args){
    ReadVersion readVersion = new ReadVersion();
    readVersion.readVersionInfoInManifest();
  }
  
  public void readVersionInfoInManifest(){
    
    //build an object whose class is in the target jar
    InternetAddress object = new InternetAddress();
    
    //navigate from its class object to a package object
    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);
  }
} 
Example output of this class:

Package name: JavaMail(TM) API Design Specification
Package version: 1.3