のパッケージクラスjava.lang.Packageには、必要な操作を行うメソッドがあります。ここでは、Javaコードを使用して、マニフェストの内容を取得する簡単な方法は次のとおりです。
String t = this.getClass().getPackage().getImplementationTitle();
String v = this.getClass().getPackage().getImplementationVersion();
私は共有ユーティリティclass.The方法で静的メソッドにこれを入れ、パラメータとしてクラスハンドルオブジェクトを受け取ります。こうすることで、システム内のどのクラスでも必要なときに独自のマニフェスト情報を取得できます。明らかに、このメソッドは、値の配列またはハッシュマップを返すように簡単に変更できます。
呼び出し方法:
String ver = GeneralUtils.checkImplVersion(this);
GeneralUtils.javaと呼ばれるファイル内のメソッド:
public static String checkImplVersion(Object classHandle)
{
String v = classHandle.getClass().getPackage().getImplementationVersion();
return v;
}
そして、あなたがパッケージを経由して取得することができます以外のマニフェストのフィールド値を取得しますクラス(例えばあなた自身のビルド - 日付)、あなたは、メインアトリビュートを取得し、それらを介して、あなたが望む特定のものを求める。以下のコードは私が見つけた似たような質問からのわずかな改造ですが、おそらくここにあります。
これをtry-catchブロックに入れ、メソッドにclassHandle( "this"またはMyClass.class)を渡します。 "classHandleは" Class型は次のとおりです。いくつかのケースで...class.getProtectionDomain().getCodeSource().getLocation();
がvfs:/
でパスを与えるので、これはさらに処理する必要がありますので
String className = getClass().getSimpleName() + ".class";
String classPath = getClass().getResource(className).toString();
if (!classPath.startsWith("jar")) {
return DEFAULT_PROPERTY_VALUE;
}
URL url = new URL(classPath);
JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
Manifest manifest = jarConnection.getManifest();
Attributes attributes = manifest.getMainAttributes();
return attributes.getValue(PROPERTY_NAME);
:
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;
の可能性のある重複http://stackoverflow.com/questions/2198525/can-values-defined-in-manifest-mf-be-accessed-programmatically/2198542 –