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

前端 未结 3 556
南笙
南笙 2021-02-13 23:01

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

3条回答
  •  猫巷女王i
    2021-02-13 23:23

    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
    

提交回复
热议问题