Accessing Manifest File of a JAR in Dynamic Environments
Retrieving the Manifest file of a JAR becomes challenging when the application is launched from dynamic environments like applets or webstart. The standard approach using getClass().getClassLoader().getResources(...) returns the Manifest from the first JAR loaded into the runtime, not the one hosting the target class.
To overcome this, two methods can be explored:
1. Iterate Through Resource URLs:
Iterate through the URLs returned by getResources(), reading each as a manifest until the desired one is found.
Enumeration<URL> resources = getClass().getClassLoader() .getResources("META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { try { Manifest manifest = new Manifest(resources.nextElement().openStream()); // Check if it's the target manifest and perform necessary actions. } catch (IOException E) { // Handle exception. } }
2. Utilize findResource Method:
If the class loader is an instance of java.net.URLClassLoader (such as AppletClassLoader), cast it and call findResource() directly, which is known to return the Manifest for applets.
URLClassLoader cl = (URLClassLoader) getClass().getClassLoader(); try { URL url = cl.findResource("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(url.openStream()); // Use the manifest. } catch (IOException E) { // Handle exception. }
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!