Java Jar File Find findJar(Class klass)

Here you can find the source of findJar(Class klass)

Description

find Jar

License

Apache License

Declaration

@Nullable
    public static String findJar(Class<?> klass) 

Method Source Code

//package com.java2s;
/*/*from  ww  w. ja  v a  2 s  .c  om*/
 * Hivemall: Hive scalable Machine Learning Library
 *
 * Copyright (C) 2015 Makoto YUI
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.IOException;

import java.net.URL;
import java.net.URLDecoder;

import java.util.Enumeration;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class Main {
    @Nullable
    public static String findJar(Class<?> klass) {
        String className = klass.getName();
        ClassLoader cl = klass.getClassLoader();
        return findJar(className, cl);
    }

    /**
     * Returns the full path to the Jar containing the class.
     *
     * @param klass class.
     * @return path to the Jar containing the class.
     */
    @Nullable
    public static String findJar(@Nonnull String klass, @Nullable ClassLoader loader) {
        if (loader != null) {
            String class_file = klass.replaceAll("\\.", "/") + ".class";
            try {
                for (Enumeration<URL> itr = loader.getResources(class_file); itr.hasMoreElements();) {
                    URL url = itr.nextElement();
                    String path = url.getPath();
                    if (path.startsWith("file:")) {
                        path = path.substring("file:".length());
                    }
                    path = URLDecoder.decode(path, "UTF-8");
                    if ("jar".equals(url.getProtocol())) {
                        path = URLDecoder.decode(path, "UTF-8");
                        return path.replaceAll("!.*$", "");
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}

Related

  1. findContainingJar(Class my_class)
  2. findContainingJar(Class clazz)
  3. findContainingJar(Class clazz)
  4. findContainingJar(Class myClass, Map packagedClasses)
  5. findContainingJar(ClassLoader classLoader, String resourceName)
  6. findJar(Class my_class)
  7. findJar(File dir)
  8. findJar(String nameRegexp)
  9. findJarContaining(Class c)