Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I discover which classpath entry provided a class?

I am loading several different classes from several different .jars from a custom class loader in Java. I create a custom URLClassLoader, add several .jars to it and pass it on to a ServiceLoader to find the classes I want.

My question is: given a class, is there a way to discover which .jar it was loaded from?

like image 754
John Without Arms Avatar asked Nov 22 '25 21:11

John Without Arms


2 Answers

The following snippet should work:

obj.getClass().getProtectionDomain().getCodeSource().getLocation().toString()

Note that you should add checks for null when calling getProtectionDomain or getCodeSource and handle appropriately in any production code. (It depends on the class loader, security, etc.)

like image 168
ars Avatar answered Nov 25 '25 11:11

ars


Try setting the parameter

-verbose:class

when running your jar/class using java and it will give you a full rundown of the classes it loads and their origin, e.g:

[Opened /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/sunrsasign.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jsse.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jce.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/charsets.jar]
[Loaded java.lang.Object from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.io.Serializable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]

That should give you all you need to know to find the class/jar you want.

like image 38
Jon Avatar answered Nov 25 '25 09:11

Jon