Reading my own Jar's Manifest

Houtman picture Houtman · Aug 13, 2009 · Viewed 123.6k times · Source

I need to read the Manifest file, which delivered my class, but when I use:

getClass().getClassLoader().getResources(...)

I get the MANIFEST from the first .jar loaded into the Java Runtime.
My app will be running from an applet or a webstart,
so I will not have access to my own .jar file, I guess.

I actually want to read the Export-package attribute from the .jar which started the Felix OSGi, so I can expose those packages to Felix. Any ideas?

Answer

ZZ Coder picture ZZ Coder · Aug 13, 2009

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");