java.lang.Package 中的Package 类有方法来做你想做的事。这是使用您的 java 代码获取清单内容的简单方法:
String t = this.getClass().getPackage().getImplementationTitle();
String v = this.getClass().getPackage().getImplementationVersion();
我把它放到一个共享实用程序类的静态方法中。该方法接受一个类句柄对象作为参数。这样,我们系统中的任何类都可以在需要时获取自己的清单信息。显然,可以轻松修改该方法以返回值的数组或哈希图。
调用方法:
String ver = GeneralUtils.checkImplVersion(this);
GeneralUtils.java 文件中的方法:
public static String checkImplVersion(Object classHandle)
{
String v = classHandle.getClass().getPackage().getImplementationVersion();
return v;
}
并且要获得除了可以通过 Package 类获得的那些字段值以外的清单字段值(例如,您自己的 Build-Date),您需要获得主要属性并通过这些属性来处理,询问您想要的特定属性。下面的代码是我发现的一个类似问题的一个小修改,可能在 SO 上。 (我想记下它,但我把它弄丢了 - 抱歉。)
将 this 放入 try-catch 块中,将 classHandle(“this”或 MyClass.class )传递给方法。 "classHandle" 是 Class 类型:
String buildDateToReturn = null;
try
{
String path = classHandle.getProtectionDomain().getCodeSource().getLocation().getPath();
JarFile jar = new JarFile(path); // or can give a File handle
Manifest mf = jar.getManifest();
final Attributes mattr = mf.getMainAttributes();
LOGGER.trace(" --- getBuildDate: "
+"\n\t path: "+ path
+"\n\t jar: "+ jar.getName()
+"\n\t manifest: "+ mf.getClass().getSimpleName()
);
for (Object key : mattr.keySet())
{
String val = mattr.getValue((Name)key);
if (key != null && (key.toString()).contains("Build-Date"))
{
buildDateToReturn = val;
}
}
}
catch (IOException e)
{ ... }
return buildDateToReturn;