我可以在运行时确定Java库的版本吗? [英] Can I determine the version of a Java library at runtime?

查看:61
本文介绍了我可以在运行时确定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

这篇关于我可以在运行时确定Java库的版本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆