MANIFEST.MF属性返回null

时间:2016-04-10 11:40:02

标签: java attributes manifest

我正在尝试从MANIFEST.MF文件中获取一些属性,但它们返回null。

清单

Manifest-Version: 1.0

Archiver-Version: Plexus Archiver 
Built-By: jenkins 
Build-Time: 2016-04-09T18:02:46Z Class-Path: spigot-1.8-R0.1-SNAPSHOT.jar Created-By: Apache Maven 3.3.9 
Build-Jdk: 1.8.0_77

Name: Build Details 
Implementation-SCM-Revision: SomeCommit 
Implementation-Build-Number: SomeBuildNumber 
Implementation-Title: SomeTitle 
Implementation-Version: 4.0.0-SNAPSHOT

代码(此代码不是使用的确切代码,但几乎相同)

首先尝试

 public void doStuff() {
    String version;
    InputStream stream = Main.class.getClassLoader().getResourceAsStream("META-INF/MANIFEST.MF");
    Properties properties = new Properties();

    if (stream != null) {
        try {
            properties.load(stream);

            version = properties.getProperty("Implementation-SCM-Revision"); //This is null 
        } catch (IOException ex) {
            //TODO handle exception
        }
    }

第二次尝试

public void doStuff() {
    Enumeration resEnum;
    try {
        resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
        while (resEnum.hasMoreElements()) {
            try {
                URL url = (URL)resEnum.nextElement();
                InputStream is = url.openStream();
                if (is != null) {
                    Manifest manifest = new Manifest(is);
                    Attributes mainAttribs = manifest.getMainAttributes();
                    String version = mainAttribs.getValue("Implementation-SCM-Revision"); //This is null
                }
            }
            catch (Exception e) {
            }
        }
    } catch (IOException e1) {
    }
}

问题在于,当来自Attributes #getMainAttributes()的所有键被打印出来时,它会打印[Archiver-Version, Implementation-Title, Sealed, Specification-Version, Implementation-Version, Created-By, Manifest-Version, Build-Jdk, Specification-Vendor, Implementation-Vendor, Ant-Version, Specification-Title, Built-By, Main-Class],它会排除Implementation-SCM-Revision之类的内容。那是我想要的。

没有生成堆栈跟踪,只是在打印null属性时在控制台中打印Implementation-SCM-Revision

1 个答案:

答案 0 :(得分:0)

即使困难,Oracle也设法打破了Manifest类:

https://bugs.openjdk.java.net/browse/JDK-8201636