Skip to content

Instantly share code, notes, and snippets.

@sakamotodesu
Created October 31, 2013 13:19
Show Gist options
  • Save sakamotodesu/7249556 to your computer and use it in GitHub Desktop.
Save sakamotodesu/7249556 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.net.URL;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
public class FromManifest {
public String getVersion() {
String version = "null";
final Class target = this.getClass();
final URL location = target.getResource("/" + target.getName().replaceAll("\\.", "/") + ".class");
// Jarファイルにしてから実行するとpathの中身はこんなかんじ file:/C:/temp/test/lib/test-1.0.0.jar!/com/test/FromManifest.class
// Eclipseなどでクラスファイルから直接呼び出すと/C:/temp/test/build/classes/main/com/test/FromManifest.class
final String path = location.getPath();
if (path.matches("^file:.*jar\\!.*")) {
String jarPath = (path.substring(0, path.lastIndexOf("jar!")) + "jar").substring(6);
try {
final JarFile jarFile = new JarFile(jarPath);
final Manifest mf = jarFile.getManifest();
final Attributes attributes = mf.getMainAttributes();
version = attributes.getValue("Implementation-Version");
jarFile.close();
} catch (IOException e) {
e.getStackTrace();
}
}
return version;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment