Java Jar File Find getJarFile(Class clazz)

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

Description

Returns null or the jar-file containing the given class.

License

Open Source License

Declaration

public static File getJarFile(Class<?> clazz) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.net.URL;

public class Main {
    /**//  w w w  .  jav  a2  s . co  m
     * Returns null or the jar-file containing the given class.
     */
    public static File getJarFile(Class<?> clazz) {

        URL jarUrl = (clazz.getProtectionDomain().getCodeSource() == null ? null
                : clazz.getProtectionDomain().getCodeSource().getLocation());
        File jarFile = null;
        if (jarUrl != null) {
            jarFile = getFile(jarUrl);
            if (!jarFile.isFile()) {
                jarFile = null;
            }
        }
        return jarFile;
    }

    /**
     * Converts the url to a file.
     */
    public static File getFile(final URL url) {

        if (url == null)
            return null;
        File f = null;
        try {
            f = new File(url.toURI());
        } catch (Exception e) {
            f = new File(url.getPath());
        }
        return f;
    }
}

Related

  1. findJarsFromDirectory(File targetDirectory)
  2. findJarsNamesInPath(String path)
  3. getJarFile(@Nonnull Class clazz)
  4. getJarFile(Class clazz)
  5. getJarFile(Class clazz)
  6. getJarFile(final ClassLoader loader)
  7. getJarFile(String classPath)
  8. getJarFileByResourceName(Class clazz, String resourceName)
  9. getJarFolder(Class clazz)