Search code examples
javaosgimanifest.mfapache-felix

Reading my own Jar's Manifest


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?


Solution

  • You can do one of two things:

    1. 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());
             // If the line above leads to <null> manifest Attributes try from JarInputStream:
             // Manifest manifest = resources.nextElement().openStream().getManifest();
      
             // check that this is your manifest and do what you need or get the next one
             ...
           } catch (IOException E) {
             // handle
           }
       }
      
    2. You can try checking whether getClass().getClassLoader() is an instance of java.net.URLClassLoader. Majority of Sun classloaders are, including AppletClassLoader. You can then cast it and call findResource() 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
       }