djechlin
djechlin

Reputation: 60748

Programmatically access MANIFEST.MF of main class

Is this possible without knowledge of the name of the main class? In particular I am after the Implementation Version property that I want sent in an info email on application startup. The only ways I know to access this require knowing the package or the name of the jar file whose information I want to access; I do not know how to do it simply by looking for the main class.

Upvotes: 2

Views: 1798

Answers (2)

Gus
Gus

Reputation: 3554

The comments from @Lee Meador point at good hints for finding your Manifest. You don't need to know the jar name, you just need to be able to identify your manifest. Suggestion: use any combination of the other IMPLEMENTATION_* attributes to identify the correct manifest. If you're already setting IMPLEMENTATION_VERSION, why not also set IMPLEMENTATION_NAME so you can find it. Once you've got it, you can look through the entries to find the one you want. The Manifest APImakes it even easier:

            Attributes mainAtts = mf.getMainAttributes();
        if(mainAtts.containsKey(Attributes.Name.MAIN_CLASS)){
            String mainClass = mainAtts.getValue(Attributes.Name.MAIN_CLASS);
            System.out.println(mainClass);
            String mainVer = mainAtts.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
            System.out.println(mainVer);
        }

Upvotes: 1

Christopher Schultz
Christopher Schultz

Reputation: 20837

So you want to know about the main class but don't want to know what it's name is?

In order to find what you're looking for, you need to:

  1. Identify the main class (sorry, this will be a requirement)
  2. Find out where that class was loaded
  3. If it's a JAR file, load the manifest from that JAR file

Step 1 might be difficult: the thread that launched the main class might have finished -- for instance, many GUI programs will execute a Class.main(String[]) method and then terminate while the AWT thread keeps the process alive. You might not be able to identify the main class at all. If that's the case, you are probably out of luck. You could try the sun.java.command system property, but that is probably only valid on Sun/Oracle JVMs.

Step 2 is fairly easy: get the Class's ClassLoader, then ask for the URL of the .class file itself.

Step 3 is also fairly easy: open the JAR file and look for the META-INF/MANIFEST.MF file.

Upvotes: 0

Related Questions