Search code examples
javajarclassclassloader

Determine which JAR file a class is from


I am not in front of an IDE right now, just looking at the API specs.

CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
    URL jar = src.getLocation();
}

I want to determine which JAR file a class is from. Is this the way to do it?


Solution

  • Yes. It works for all classes except classes loaded by bootstrap classloader. The other way to determine is:

    Class klass = String.class;
    URL location = klass.getResource('/' + klass.getName().replace('.', '/') + ".class");
    

    As notnoop pointed out klass.getResource() method returns the location of the class file itself. For example:

    jar:file:/jdk/jre/lib/rt.jar!/java/lang/String.class
    file:/projects/classes/pkg/MyClass$1.class
    

    The getProtectionDomain().getCodeSource().getLocation() method returns the location of the jar file or CLASSPATH

    file:/Users/home/java/libs/ejb3-persistence-1.0.2.GA.jar
    file:/projects/classes