Get a JAR Version Programmatically in Java


A jar file is simply a group of class files and their associated resources compressed in one file. 

When a defect occurs, one of the first questions we ask is what is the deployed version of a specific jar file

During an application startup, it might be a good idea to log the version numbers of all used jars. This can be very useful for debugging problems later on.

Some high-level information about a jar can be found in the MANIFEST file, which is basically, a text file included with each jar. The MANIFEST file usually includes version information. We can get this information programmatically using methods of the Package class.

 

How to read manifest file from jar using java

For example, we can have a method, called during the application startup, that gets the version information from the Manifest.

Let’s suppose that our application is using a Student object, whose class is in a separate jar

public void getVersionFromManifest(){

    

    //we need to build an instance of Student, whose class is in the target jar

    Student object = new Student();

    

    //get the corresponding package object

    Package objPackage = object.getClass().getPackage();

    

    //getting information from the package object 

    System.out.println("Package Implementation version: " +objPackage.getImplementationVersion());

    System.out.println("Package specification version: " +objPackage.getSpecificationVersion());


  }

 

 

What is the Difference between Specification version and Implementation version?

 

As described in the documentation of java.lang.Package:

  • getImplementationVersion returns the version of this implementation. It consists of any string assigned by the vendor of this implementation and does not have any particular syntax specified or expected by the Java runtime
  • getSpecificationVersion: Returns the version number of the specification that this package implements. This version string must be a sequence of non-negative decimal integers separated by “.”‘s and may have leading zeros.

 

Recent Posts