You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在运行时确定Java库及第三方Java库的版本?

当然可以在运行时确定Java库的版本——不管是JDK自带的标准库,还是你引入的各种第三方依赖,都有对应的可行方案,我给你详细拆解一下:

一、确定JDK标准库的版本

JDK自带的标准库有几种简单可靠的方式获取版本:

  • 通过系统属性获取整体版本
    直接使用System.getProperty()读取JDK相关的系统属性,这是最常用的方式:
// 获取JDK的完整版本号(比如1.8.0_381、17.0.8)
String jdkFullVersion = System.getProperty("java.version");
// 获取Java规范版本(比如8、17,对应Java 8、Java 17)
String javaSpecVersion = System.getProperty("java.specification.version");
// 获取JDK的厂商信息
String jdkVendor = System.getProperty("java.vendor");

System.out.println("JDK完整版本: " + jdkFullVersion);
System.out.println("Java规范版本: " + javaSpecVersion);
  • 针对Java 9+模块化的模块版本获取
    从Java 9开始引入模块化系统,每个标准模块(比如java.base、java.util)都有自己的版本信息,可以通过Module API获取:
// 获取java.base核心模块的版本
Module baseModule = Object.class.getModule();
ModuleDescriptor descriptor = baseModule.getDescriptor();
descriptor.version().ifPresent(version -> 
    System.out.println("java.base模块版本: " + version)
);
二、确定第三方Java库的版本

第三方库的版本获取方式取决于库的实现规范,常见的有以下几种:

  • 读取JAR包的MANIFEST.MF文件
    绝大多数正规的第三方库都会在JAR包的MANIFEST.MF文件中记录版本信息,比如Implementation-Version、Specification-Version字段。你可以通过目标类的类加载器来读取这个文件:
// 以Gson库为例,获取其版本
Class<?> gsonClass = com.google.gson.Gson.class;
String classResourcePath = gsonClass.getResource(gsonClass.getSimpleName() + ".class").toString();

if (classResourcePath.startsWith("jar:")) {
    // 截取JAR包的URL路径
    String jarUrl = classResourcePath.substring(4, classResourcePath.indexOf("!"));
    try (JarInputStream jarStream = new JarInputStream(new URL(jarUrl).openStream())) {
        Manifest manifest = jarStream.getManifest();
        Attributes mainAttributes = manifest.getMainAttributes();
        String gsonVersion = mainAttributes.getValue("Implementation-Version");
        System.out.println("Gson版本: " + gsonVersion);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 利用库自身提供的版本API
    很多第三方库会直接提供获取版本的静态方法或常量,比如:

    • Guava:通过类的包信息获取
      String guavaVersion = com.google.common.base.Preconditions.class.getPackage().getImplementationVersion();
      
    • Spring框架:专门提供了版本获取方法
      String springVersion = org.springframework.core.SpringVersion.getVersion();
      
    • Apache Commons Lang:通过版本枚举类获取
      String commonsLangVersion = org.apache.commons.lang3.JavaVersion.getVersion().toString();
      
  • Java 9+模块化第三方库的版本获取
    如果第三方库是模块化的(包含module-info.java),可以和标准库一样通过Module API获取版本:

Module gsonModule = com.google.gson.Gson.class.getModule();
gsonModule.getDescriptor().version().ifPresent(version -> 
    System.out.println("Gson模块版本: " + version)
);

注意: 有些不规范的第三方库可能没有在MANIFEST中写入版本,也没有提供版本API,这种情况下只能尝试通过JAR文件名(如果文件名包含版本号,比如gson-2.10.1.jar)来推断,但这种方式并不靠谱,因为文件名很容易被修改。

内容的提问来源于stack exchange,提问作者Sean Patrick Floyd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:31:16