所以我终于弄清楚了,以为我愿意和别人分享我的头,以防其他人像我那样把头撞在那堵砖墙上。我再也无法让
Package类中的方法返回除以外的任何值
null。请参阅下面的修订代码,以了解如何实现这一目标。
package com.example.package1;import java.util.*;import java.util.jar.*;import java.net.*;class myClass { public static void main(String[] args) { try { new myClass(); } catch (Exception e) { System.out.println(e.getMessage()); } finally { System.out.println("Done"); try{Thread.sleep(40000);}catch(Exception ee){} } }public myClass() throws Exception { String clz = getClass().getSimpleName() + ".class"; String pth = getClass().getResource(clz).toString(); String mnf = pth.substring(0, pth.lastIndexOf("!") + 1) + "/meta-INF/MANIFEST.MF"; String pkg = getClass().getPackage().getName().replaceAll("\.","/"); URL url = new URL(mnf); Manifest manifest = new Manifest(url.openStream()); Attributes attr = manifest.getAttributes(pkg); String value = attr.getValue("Specification-Title") + " - " + attr.getValue("Implementation-Title") + " " + attr.getValue("Specification-Version") + " build # " + attr.getValue("Implementation-Version"); System.out.println(value); }}输出:
MyPackage - MP v1.1 build # 2015-11-05-CDone
提取四段元数据的代码很多。
因此,如果您希望少写几行,这就是我使用的:
public myClass() throws Exception { Attributes attr = new Manifest(new URL(getClass().getResource(getClass().getSimpleName() + ".class").toString().substring(0, getClass().getResource(getClass().getSimpleName() + ".class").toString().lastIndexOf("!") + 1) + "/meta-INF/MANIFEST.MF").openStream()).getAttributes(getClass().getPackage().getName().replaceAll("\.","/")); String value = attr.getValue("Specification-Title") + " - " + attr.getValue("Implementation-Title") + " " + attr.getValue("Specification-Version") + " build # " + attr.getValue("Implementation-Version"); System.out.println(value);}


