Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I determine the version of a Java library at runtime?

Tags:

java

libraries

Is it possible to determine the version of a third party Java library at Runtime?

like image 710
Sean Patrick Floyd Avatar asked Apr 18 '18 00:04

Sean Patrick Floyd


1 Answers

Third party Java library means a Jar file, and the Jar file manifest has properties specifically to specify the version of the library.

Beware: Not all Jar files actually specify the version, even though they should.

Built-in Java way to read that information is to use reflection, but you need to know some class in the library to query. Doesn't really matter which class/interface.

Example

public class Test {
    public static void main(String[] args) {
        printVersion(org.apache.http.client.HttpClient.class);
        printVersion(com.fasterxml.jackson.databind.ObjectMapper.class);
        printVersion(com.google.gson.Gson.class);
    }
    public static void printVersion(Class<?> clazz) {
        Package p = clazz.getPackage();
        System.out.printf("%s%n  Title: %s%n  Version: %s%n  Vendor: %s%n",
                          clazz.getName(),
                          p.getImplementationTitle(),
                          p.getImplementationVersion(),
                          p.getImplementationVendor());
    }
}

Output

org.apache.http.client.HttpClient
  Title: HttpComponents Apache HttpClient
  Version: 4.3.6
  Vendor: The Apache Software Foundation
com.fasterxml.jackson.databind.ObjectMapper
  Title: jackson-databind
  Version: 2.7.0
  Vendor: FasterXML
com.google.gson.Gson
  Title: null
  Version: null
  Vendor: null
like image 161
Andreas Avatar answered Sep 17 '22 11:09

Andreas