About Me

My photo
Bangalore, Karnataka, India

Sunday, March 28, 2010

Finding the jar/jars from which the class/resource is loaded

There is always a very good chance of having the same class in two different jars available in the class path of the class loader. Its the fact that which ever jar comes first in the search is loaded and used. But if you wonder from which jar or path the class/resource (may be a properties file) is loaded from. Here you go. just write the following snippet of code in the context you want to know the resource location.

URL url = Thread.currentThread().getContextClassLoader().getResource("com/example/ClassToFind.class");

if(url != null){
System.out.println(" location of resource in context "+url.getPath());
} else {
url = super.getClass().getClassLoader().getResource(name);
if(url != null){
System.out.println(" location of resource class loder "+ super.getClass().getClassLoader() + " is "+ url.getPath());
}
}

If the ClassToFind.class is in example.jar then the above will print

location-of-example.jar!com/example/ClassToFind.class

If you want to find all the jars containg the resource then you can use this instead.

java.util.Enumeration urls = Thread.currentThread().getContextClassLoader()
.getResources("");

while(urls.hasMoreElements()){
System.out.println(urls.nextElement().getPath());
}

There are few other ways to get around this. If you have put Java in verbose mode or If you are running in JBOSS you can enable the class loader logs. see JBOSS docs for more information.

No comments:

Post a Comment