Tuesday, March 04, 2008

How to find which jar file contains your class at 'runtime'

If you ever wanted to know which jar your class belongs, or wanted to access the meta-information from that jar file (such as certs from Manifest.mf etc.), here's how you can do it.

    public URL getJarURL() {
URL clsUrl = getClass().getResource(getClass().getSimpleName() + ".class");
if (clsUrl != null) {
try {
URLConnection conn = clsUrl.openConnection();
if (conn instanceof JarURLConnection) {
JarURLConnection connection = (JarURLConnection) conn;
return connection.getJarFileURL();
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
return null;
}
This would work in most of the enterprisely Java environment (unless your classloader is hacked by some stupid framework in between), not sure if this would be valid under OSGi container.

Why in the name of programming I need to write such trivial hacks? O Java Module system (JSR277), I await you.

Note: This is the simplest way I could write, if you know smarter way, feel free to comment here.

4 comments:

KetanPadegaonkar said...

That's an interesting piece of snippet.

I use a shell script that essentially grepped through the list of all stuff in a jar.

asolntsev said...

Hi Nirav,
I know a simplier way.

There is a term called "Code source" for what are you looking for.

Look:

http://asolntsev.blogspot.com/2008/03/how-to-find-which-jar-file-contains.html

Nirav Thaker said...

@Asolntsev
Wow, I introspected protection domain before writing this piece but never knew about getCodeSource() method. Thanks!

@Ketan,
That's interesting. Not sure if it would handle inner classes well (A$B)...

JP @ wait and notify in java said...

quite a nice utility. very useful while debugging classpath related issue in Java .

Thanks
Javin