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

m. *_*khm 5 java eclipse jar

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

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

为了获得软件包的实现版本,我尝试使用最简单直接的方法:

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

根据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库的包,它返回正确的值.也许我错过了关于如何在清单中命名包的详细信息,或者JarRsrcLoader与之相关的原因- 可能需要一些特殊的语法来解决包.我也尝试过".com/domain/...","/com/domain/..."并且".../controller",甚至"rsrc:./com/domain..."在清单的包名-均无功而返.我可以使用其他方法,例如将清单加载为流并使用Manifest类解析它,但我想了解使用该getImplementationVersion()方法的正确方法.

Tom*_*Tom 6

解决了!至少对我来说 :) 您需要确保有问题的包仅位于一个 JAR 中,并且该 JAR 具有正确的清单。

这是有道理的,因为您查询包的版本,如果该包存在于许多具有不同或部分未设置实现版本的 JAR 中,那么 JVM 应该返回什么?


Rad*_*FID 5

您可以从 classLoader 读取清单文件并获取您需要的值,如下所示:

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