Saturday, June 10, 2006

How do you print the java classpath?

java servlet "print classpath"

This requirement came in trying to diagnose the previous post. It'd be quite useful in a any enterprise/web application to be able to see the classpath in use (perhaps via an administration page).

This is based on post on Java Tips (very useful site), but with the difference that your web application will have a different classloader to the system one. You'll need the classloader being used by a class within the web application (such as the one responsible for producing your admin-output).

 public String getClasspathString() {
     StringBuffer classpath = new StringBuffer();
     ClassLoader applicationClassLoader = this.getClass().getClassLoader();
     if (applicationClassLoader == null) {
         applicationClassLoader = ClassLoader.getSystemClassLoader();
     URL[] urls = ((URLClassLoader)applicationClassLoader).getURLs();
      for(int i=0; i < urls.length; i++) {
      return classpath.toString();


Anonymous said...

Very nice post

Philippe said...

Or... System.getProperty("java.class.path")

Kevin Jansz said...

Thanks @Philippe, but in a servlet container (like Tomcat) System.getProperty("java.class.path") will only give you "[CATALINA_BASE]\bin\bootstrap.jar" (and nothing more) ... the above detail will give you the full classpath for the classloader of the web application.