Determine which JAR file a class is from

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("https://stackoverflow.com/" + klass.getName().replace('.', "https://stackoverflow.com/") + ".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

Leave a Comment