Reading the Manifest of Your Own Jar
Accessing the Manifest file associated with your own class can be a challenge, especially when using getClass().getClassLoader().getResource(...). This method may return the manifest from a different .jar file if called from an applet or webstart environment.
To overcome this limitation, consider the following solutions:
1. Iterating Through Manifest URLs
Iterate through the URLs returned by getResource(...) and read them as manifests until you find the correct one:
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 } }
2. Using URLClassLoader
If getClass().getClassLoader() is an instance of java.net.URLClassLoader, you can cast it and use findResource(...):
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 }
This approach has been known to return the correct manifest for applets.
The above is the detailed content of How to Access the Manifest of Your Own Jar in Java?. For more information, please follow other related articles on the PHP Chinese website!