Sunday, March 13, 2011

Determine jar file of a class

We sometimes need to determine from which jar file some particular class comes from. Here I wrote a small method to find out the name of the jar file we are looking for :

public static String getJarURL(Class mclass) {

URL clsUrl = mclass.getResource(mclass.getSimpleName() + ".class");

if (clsUrl != null) {

try {

URLConnection conn = clsUrl.openConnection();

if (conn instanceof JarURLConnection) {

JarURLConnection connection = (JarURLConnection) conn;

return connection.getJarFileURL().toString();

}

}

catch (IOException e) {

throw new RuntimeException(e);

}

}

return null;

}



public static void main(String[] x){

System.out.println(getJarURL(java.net.HttpURLConnection.class));

}



 

which prints following output :

file:/C:/Program%20Files%20(x86)/Java/jre1.5.0_22/lib/rt.jar

No comments: