Retrieves the manifest information for the jar file which contains this utility class. - Java Reflection

Java examples for Reflection:Jar

Description

Retrieves the manifest information for the jar file which contains this utility class.

Demo Code

/*/*from w  w  w  . j  a v  a 2  s  .  c om*/
 * Copyright 2002 - 2013 Pentaho Corporation.  All rights reserved.
 * 
 * This software was developed by Pentaho Corporation and is provided under the terms
 * of the Mozilla Public License, Version 1.1, or any later version. You may not use
 * this file except in compliance with the license. If you need a copy of the license,
 * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. TThe Initial Developer is Pentaho Corporation.
 *
 * Software distributed under the Mozilla Public License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or  implied. Please refer to
 * the license for the specific language governing your rights and limitations.
 */
import java.net.URL;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;

public class Main{
    /**
     * Retrieves the manifest information for the jar file which contains this utility class.
     * 
     * @return The Manifest file for the jar file which contains this utility class, or <code>null</code> if the code is
     *         not in a jar file.
     */
    public static Manifest getManifest() {
        return getManifest(ManifestUtil.class);
    }
    /**
     * Retrieves the manifest information for the jar file which contains the specified class.
     * 
     * @return The Manifest file for the jar file which contains the specified class, or <code>null</code> if the code is
     *         not in a jar file.
     */
    @SuppressWarnings("rawtypes")
    public static Manifest getManifest(Class clazz) {
        Manifest retval = null;
        JarInputStream jin = null;
        try {
            final URL codeBase = clazz.getProtectionDomain()
                    .getCodeSource().getLocation();
            if (codeBase.getPath().endsWith(".jar")) { //$NON-NLS-1$
                jin = new JarInputStream(codeBase.openStream());
                retval = jin.getManifest();
                jin.close();
            }
        } catch (Exception e) {
            return null;
        } finally {
            if (jin != null) {
                try {
                    jin.close();
                } catch (Exception ex) {
                    // should log something here...
                    retval = null;
                }
            }
        }
        return retval;
    }
}

Related Tutorials