Java Jar File Find getJarFile(Class clazz)

Here you can find the source of getJarFile(Class clazz)

Description

Obtains the jar file that contains the class in question.

License

CDDL license

Parameter

Parameter Description
clazz The given class

Return

The jar file containing the class, or null if the class is not local or not loaded from a jar file

Declaration

public static File getJarFile(Class clazz) 

Method Source Code

//package com.java2s;
/* The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License). You may not use this file except in
 * compliance with the License.//from w  ww. jav a2s  . c  om
 *
 * You can obtain a copy of the License at
 * http://www.sun.com/cddl/cddl.html or
 * install_dir/legal/LICENSE
 * See the License for the specific language governing
 * permission and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at install_dir/legal/LICENSE.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * $Id: Utilities.java,v 1.15.2.2 2009/09/21 04:59:50 akara Exp $
 *
 * Copyright 2005-2009 Sun Microsystems Inc. All Rights Reserved
 */

import java.io.File;
import java.net.URL;

public class Main {
    /**
     * Obtains the jar file that contains the class in question.
     * @param clazz The given class
     * @return The jar file containing the class, or null if the class is not
     *         local or not loaded from a jar file
     */
    public static File getJarFile(Class clazz) {
        String resName = clazz.getName();
        resName = "/" + resName.replace('.', '/') + ".class";
        // Sample URL: jar:file:/opt/faban/benchmarks/web101/lib/web101.jar!/sample/driver/WebDriver.class
        URL classURL = clazz.getResource(resName);
        if (classURL == null)
            return null;
        String jarHeader = "jar:file:";
        String urlString = classURL.toString();

        if (!urlString.startsWith(jarHeader))
            return null;

        int bangIdx = urlString.indexOf('!', jarHeader.length());
        String jarPath = urlString.substring(jarHeader.length(), bangIdx);
        File jarFile = new File(jarPath);
        if (!jarFile.exists())
            return null;

        return jarFile;
    }
}

Related

  1. findJars(File libDir)
  2. findJarsDir(String sparkHome, String scalaVersion, boolean failIfNotFound)
  3. findJarsFromDirectory(File targetDirectory)
  4. findJarsNamesInPath(String path)
  5. getJarFile(@Nonnull Class clazz)
  6. getJarFile(Class clazz)
  7. getJarFile(Class clazz)
  8. getJarFile(final ClassLoader loader)
  9. getJarFile(String classPath)