public URL getJarURL() {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.
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;
}
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:
That's an interesting piece of snippet.
I use a shell script that essentially grepped through the list of all stuff in a jar.
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
@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)...
quite a nice utility. very useful while debugging classpath related issue in Java .
Thanks
Javin
Post a Comment