Java getting the class path in the runtime
March 26, 2012 in Java
In some cases, you may need to know for debugging purposes from where a specific class is loaded. This happens usually if there are two different versions of the class in the class path (the one used in compilation is different from the one used in the runtime) which results in the popular java.lang.NoClassDefFoundError error).
Thanks to the ProtectionDomain, you can get this information as shown below.
try {
Class myclass = Class.forName("org.apache.commons.logging.Log"); /*or any other class you wish*/
System.out.println(myclass.getProtectionDomain().getCodeSource()
.getLocation());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
I can’t remember where I got this code or part of it, but it does exactly what you showed in your post. – https://gist.github.com/1554685