views:

136

answers:

3

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?

+3  A: 

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.

Jon
Oh, no, I don't want to track down issues. I actually want to find where the .jar is so I can do stuff relative to it's path during runtime.
John Without Arms
Ok, well your issue is the location of the jar I guess. Anyways, it should give you the exact path of the JAR you want regardless...
Jon
I'm sorry if I wasn't clear enough.If I use your -verbose method it will send that info to the stdout, correct? I needed it inside the code during runtime to perform file operations relative to its path. My code needs that information, not me :)
John Without Arms
+2  A: 

You can call findResource on Classloader, and parse the URL that you get to figure out where it is coming from.

Yishai
This worked for me using `Thread.currentThread().getContextClassLoader().findResource("MyClass.class")`. Thank you very much!
John Without Arms
+4  A: 

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.)

ars