get Jar Path from loaded class - Java Reflection

Java examples for Reflection:Class

Description

get Jar Path from loaded class

Demo Code


//package com.java2s;

import java.net.URL;
import java.util.Enumeration;

public class Main {
    public static void main(String[] argv) throws Exception {
        String pkg = "java2s.com";
        System.out.println(getJarPath(pkg));
    }/*from w  w w  .jav  a  2 s  .  c  om*/

    public static URL getJarPath(String pkg) {
        try {
            Enumeration<URL> resources = Thread.currentThread()
                    .getContextClassLoader()
                    .getResources(pkg.replace('.', '/'));
            while (resources.hasMoreElements()) {
                URL url = (URL) resources.nextElement();
                return url;
            }
            return null;
        } catch (Exception e) {
            throw (e instanceof RuntimeException) ? (RuntimeException) e
                    : new RuntimeException(e);
        }
    }
}

Related Tutorials