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?
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With