Reading my own Jar's Manifest
You can find the URL for your class first. If it's a JAR, then you load the manifest from there. For example,
Class clazz = MyClass.class;
String className = clazz.getSimpleName() + ".class";
String classPath = clazz.getResource(className).toString();
if (!classPath.startsWith("jar")) {
// Class not from JAR
return;
}
String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) +
"/META-INF/MANIFEST.MF";
Manifest manifest = new Manifest(new URL(manifestPath).openStream());
Attributes attr = manifest.getMainAttributes();
String value = attr.getValue("Manifest-Version");
You can do one of two things:
Call
getResources()
and iterate through the returned collection of URLs, reading them as manifests until you find yours:Enumeration<URL> resources = getClass().getClassLoader() .getResources("META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { try { Manifest manifest = new Manifest(resources.nextElement().openStream()); // check that this is your manifest and do what you need or get the next one ... } catch (IOException E) { // handle } }
You can try checking whether
getClass().getClassLoader()
is an instance ofjava.net.URLClassLoader
. Majority of Sun classloaders are, includingAppletClassLoader
. You can then cast it and callfindResource()
which has been known - for applets, at least - to return the needed manifest directly:URLClassLoader cl = (URLClassLoader) getClass().getClassLoader(); try { URL url = cl.findResource("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(url.openStream()); // do stuff with it ... } catch (IOException E) { // handle }
You can use Manifests
from jcabi-manifests and read any attribute from any of available MANIFEST.MF files with just one line:
String value = Manifests.read("My-Attribute");
The only dependency you need is:
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-manifests</artifactId>
<version>0.7.5</version>
</dependency>
Also, see this blog post for more details: http://www.yegor256.com/2014/07/03/how-to-read-manifest-mf.html