Alex Barker
Alex Barker

Reputation: 4400

Reading a Jar's Manifest on OS X

I have the following manifest in a jar file:

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.9.3
Created-By: 1.7.0_67-b01 (Oracle Corporation)
Main-Class: tld.project.Example

Name: tld/project
Specification-Title: Example
Specification-Version: 1.0
Specification-Vendor: Me
Implementation-Title: tld.project
Implementation-Version: 20140913
Implementation-Vendor: Me

I use the following to read some attributes from the manifest at runtime:

// Try and load the Jar manifest as a resource stream.
InputStream manInputStream = Example.class.getResourceAsStream("/META-INF/MANIFEST.MF");
if (manInputStream != null) {
    // Try and extract a version string from the Manifest.
    Manifest manifest = new Manifest(manInputStream);

    Attributes attributes = manifest.getAttributes("tld/project");

Why does the above code set attributes to null, but only on OS X? (1.7.51) If I check manifest.getEntries().size() it also returns zero, but again, this works as expected on Windows and Linux. Any ideas?

Upvotes: 1

Views: 518

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122394

Example.class.getResourceAsStream won't necessarily look in the same jar file that contains Example.class, it'll search through all the JARs available on the class loader and give you the first matching resource it finds. This isn't Mac OS specific, it's the same rule on all platforms, but presumably your classpath is in a different order when you run on mac compared to on windows or Linux and you're getting the manifest from a different jar.

You can use getResource to see which manifest you're actually loading.

If you specifically want the jar that contains Example.class you can find it with

Example.class.getProtectionDomain().getCodeSource().getLocation()

Upvotes: 2

Related Questions