If you've ever wondered where the Tomcat class-loader got a particular class from (and which of us hasn't been), or were stumped by a NoSuchMethod exception, this may be of use to you.
There are plenty of sites that will explain the rules by which Tomcat loads classes, but what I really needed was code that would give me programmatic access to the effective classpath of my webapp at runtime, so that I could figure out what the heck was happening. Not finding such code anywhere (though I'm sure it's out there somewhere), I wrote it:
private String cpString() {
int i = 0;
StringBuilder sb = new StringBuilder();
for (URLClassLoader cl = (URLClassLoader) getClass().getClassLoader();
cl != null;
cl = (URLClassLoader)cl.getParent()){
sb.append("\nclassloader level ").append(i++).append(":\n");
for (URL url: cl.getURLs())
sb.append(url.toString()).append("\n");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
This should work in any Java application, though you'll probably have to change the type of the class-loader, and perhaps substitute something else for getURLs().
No comments:
Post a Comment