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

Sea*_*oyd 8 java libraries

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

And*_*eas 14

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

注意:并非所有Jar文件都实际指定了版本,即使它们应该.

读取该信息的内置Java方式是使用反射,但是您需要知道库中的某些类来进行查询.哪个类/接口并不重要.

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

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
Run Code Online (Sandbox Code Playgroud)


Sea*_*oyd 5

尽管没有通用标准,但存在适用于大多数开放源代码库或适用于通过Maven版本插件或兼容机制通过Maven存储库发布的任何内容的黑客工具。由于JVM上的其他大多数构建系统都是Maven兼容的,因此这也应适用于通过Gradle或Ivy分发的库(可能还有其他)。

Maven的版本插件(和所有兼容的过程)中创建一个名为释放罐一个文件META-INF/${groupId}.${artifactId}/pom.properties,它包含的属性groupIdartifactIdversion

通过检查此文件并进行解析,我们可以检测到大多数库版本的版本。示例代码(Java 8或更高版本):

/**
 * Reads a library's version if the library contains a Maven pom.properties
 * file. You probably want to cache the output or write it to a constant.
 *
 * @param referenceClass any class from the library to check
 * @return an Optional containing the version String, if present
 */
public static Optional<String> extractVersion(
    final Class<?> referenceClass) {
    return Optional.ofNullable(referenceClass)
                   .map(cls -> unthrow(cls::getProtectionDomain))
                   .map(ProtectionDomain::getCodeSource)
                   .map(CodeSource::getLocation)
                   .map(url -> unthrow(url::openStream))
                   .map(is -> unthrow(() -> new JarInputStream(is)))
                   .map(jis -> readPomProperties(jis, referenceClass))
                   .map(props -> props.getProperty("version"));
}

/**
 * Locate the pom.properties file in the Jar, if present, and return a
 * Properties object representing the properties in that file.
 *
 * @param jarInputStream the jar stream to read from
 * @param referenceClass the reference class, whose ClassLoader we'll be
 * using
 * @return the Properties object, if present, otherwise null
 */
private static Properties readPomProperties(
    final JarInputStream jarInputStream,
    final Class<?> referenceClass) {

    try {
        JarEntry jarEntry;
        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
            String entryName = jarEntry.getName();
            if (entryName.startsWith("META-INF")
                && entryName.endsWith("pom.properties")) {

                Properties properties = new Properties();
                ClassLoader classLoader = referenceClass.getClassLoader();
                properties.load(classLoader.getResourceAsStream(entryName));
                return properties;
            }
        }
    } catch (IOException ignored) { }
    return null;
}

/**
 * Wrap a Callable with code that returns null when an exception occurs, so
 * it can be used in an Optional.map() chain.
 */
private static <T> T unthrow(final Callable<T> code) {
    try {
        return code.call();
    } catch (Exception ignored) { return null; }
}
Run Code Online (Sandbox Code Playgroud)

为了测试此代码,我将尝试3种类,一种来自VAVR,一种来自Guava,另一种来自JDK。

public static void main(String[] args) {
    Stream.of(io.vavr.collection.LinkedHashMultimap.class,
              com.google.common.collect.LinkedHashMultimap.class,
              java.util.LinkedHashMap.class)
          .map(VersionExtractor::extractVersion)
          .forEach(System.out::println);
}
Run Code Online (Sandbox Code Playgroud)

输出,在我的机器上:

Optional[0.9.2]
Optional[24.1-jre]
Optional.empty
Run Code Online (Sandbox Code Playgroud)