How to get the jar file location of a loaded class?

When there are two versions of the same class (same class & package name) in the classpath (may be from two different jars), there is no way to tell the JVM which one to load at runtime (JVM loads the one which it finds first). And there is no direct way of knowing from which jar the class was loaded! This causes enormous difficulties for a j2ee developer when working with different containers.

You can use the following code to find which jar was used to load the class

	public static String getClassLocation(Class clazz) {
		if(clazz == null) {
			return null;
		try {
			ProtectionDomain protectionDomain = clazz.getProtectionDomain();
			CodeSource codeSource = protectionDomain.getCodeSource();
			URL location = codeSource.getLocation();
			return location.toString();
		} catch (Throwable e) {
			return "Not found";

For example, The if you run the following code,

	public static void main(String[] args) {
		System.out.println("class location of Log: " + getClassLocation(org.apache.commons.logging.Log.class));

It will give you :

class location of Log: file:/C:/dev/tools/maven2/repository/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar

This simple code helped me a lot to resolve a lot of deployment problem in different containers specially when working with third party libs.