我可以在运行时确定Java库的版本吗?

问题描述:

是否可以在运行时确定第三方Java库的版本?

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

第三方Java库表示Jar文件,并且Jar文件清单具有专门用于指定库版本的属性.

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

当心:并非所有的Jar文件实际上都指定版本,即使它们应该.

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

Java 内置的读取该信息的方式是使用反射,但您需要知道库中的某些 类才能查询.真正无关紧要的是哪个类/接口.

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.

示例

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

输出

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