xml-commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Stefan Bodewig <bode...@apache.org>
Subject Re: What jar file was a class loaded from?
Date Tue, 18 Feb 2003 07:12:21 GMT
On Mon, 17 Feb 2003, Norman Walsh <ndw@nwalsh.com> wrote:

> Is it possible for a class to learn the location (URI) of the jar
> file from which it was loaded?

The general way (works with JDK 1.1): try to load the class file as
resource i.e. 
"/" + fully-qualified-classname.replace('.', '/') + ".class"
and go from there via something like


With JDK 1.4 you can go via class.getProtectionDomain().getCodeSource().

If URL starts with "jar:file:", the jar's name is after that prefix.
If it starts with "file:", you are looking at a directory.  In JDK 1.1
it will start with "zip:" for jars IIRC and you are out of luck when
it comes to the file name as Java uses some internal counter instead
of the name in the URL.

I'm not sure about jars loaded from the network, but this snippet here

            if (location.startsWith("jar")) {
                url = ((java.net.JarURLConnection) url.openConnection()).getJarFileURL();
                location = url.toString();

stolen from Ant which has stolen it from Axis IIUC seems to be a more
general solution for JDK >= 1.2.


View raw message