gpt4 book ai didi

java - 如何使用 Package 类的 getImplementationVersion() 方法从 JAR 的 list 中获取包版本

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:16 24 4
gpt4 key购买 nike

当我准备要部署的程序时,我将它与 Eclipse jar-in-jar 类加载器一起打包到 JAR 中。当我的程序从 JAR 运行时,我需要知道包的版本,但我无法以简单和“诚实”的方式从 jar 的 list 中获取它。 list 看起来像这样:

 Manifest-Version: 1.0
Created-By: 1.8.0_73-b02 (Oracle Corporation)
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader
Rsrc-Main-Class: com.domain.sp2.controller.Controller
Rsrc-Class-Path: ./ jar-in-jar-loader.zip javahelp-2.0.05.jar json-simple-1.1.1.jar
Class-Path: .

Name: com/domain/sp2/controller/
Implementation-Version: 19

获取包的实现版本,我尽量用最简单直接的方式:

package com.domain.sp2.controller;
public class Controller {
...
public static String getBuildNumber() throws IOException {
Package pckg = Controller.class.getPackage();
pr(pckg.getName()); // prints "com.domain.sp2.controller", as expected
return pckg.getImplementationVersion(); // returns null
}
...
}

根据 http://docs.oracle.com/javase/tutorial/deployment/jar/packageman.htmlhttp://docs.oracle.com/javase/8/docs/api/java/lang/Package.html#getImplementationVersion-- (和其他来源),它应该返回“19”,但它返回 null。对于 JRE 库的包,它返回正确的值。也许我错过了关于如何在 list 中命名包的细节,或者原因与 JarRsrcLoader 有关 - 可能需要一些特殊的语法来定位包。我也试过 ".com/domain/...", "/com/domain/..."".../controller",甚至 "rsrc:./com/domain..." 作为 list 中的包名称 - 都没有成功。我可以使用其他方式,例如将 list 作为流加载并使用 Manifest 类对其进行解析,但我想了解使用 getImplementationVersion() 方法的正确方法是什么。

最佳答案

您可以从类加载器中读取 list 文件并获取所需的值,如下所示:

URLClassLoader cl = (URLClassLoader) YOUR_CLASS.class.getClassLoader();
try {
URL url = cl.findResource("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(url.openStream());
Attributes mainAttributes = manifest.getMainAttributes();
String implVersion = mainAttributes.getValue("Implementation-Version");

System.out.println(implVersion);
} catch (IOException E) {
// handle
}

关于java - 如何使用 Package 类的 getImplementationVersion() 方法从 JAR 的 list 中获取包版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38204059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com