私はこれを理解しようと非常に多くの時間を費やしてきました。これは最も単純なことであり、Javaアプリケーションをjarで配布するすべての人がそれに対処する必要があります。
Javaアプリにバージョニングを追加して、テスト時にバージョン情報にアクセスできるようにする適切な方法を知りたいだけです。たとえば、Eclipseでのデバッグやjarからの実行などです。
これが私のbuild.xmlにあるものです:
<target name="jar" depends = "compile">
<property name="version.num" value="1.0.0"/>
<buildnumber file="build.num"/>
<tstamp>
<format property="TODAY" pattern="yyyy-MM-dd HH:mm:ss" />
</tstamp>
<manifest file="${build}/META-INF/MANIFEST.MF">
<attribute name="Built-By" value="${user.name}" />
<attribute name="Built-Date" value="${TODAY}" />
<attribute name="Implementation-Title" value="MyApp" />
<attribute name="Implementation-Vendor" value="MyCompany" />
<attribute name="Implementation-Version" value="${version.num}-b${build.number}"/>
</manifest>
<jar destfile="${build}/myapp.jar" basedir="${build}" excludes="*.jar" />
</target>
これにより/META-INF/MANIFEST.MFが作成され、Eclipseでデバッグしているときに値を読み取ることができます。
public MyClass()
{
try
{
InputStream stream = getClass().getResourceAsStream("/META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(stream);
Attributes attributes = manifest.getMainAttributes();
String implementationTitle = attributes.getValue("Implementation-Title");
String implementationVersion = attributes.getValue("Implementation-Version");
String builtDate = attributes.getValue("Built-Date");
String builtBy = attributes.getValue("Built-By");
}
catch (IOException e)
{
logger.error("Couldn't read manifest.");
}
}
ただし、jarファイルを作成すると、別のjarのマニフェストが読み込まれます(おそらく、アプリケーションによって読み込まれる最初のjar-私の場合はactivation.jar)。
また、マニフェストファイルにはすべての適切な値が含まれていますが、次のコードも機能しません。
Package thisPackage = getClass().getPackage();
String implementationVersion = thisPackage.getImplementationVersion();
何か案は?