Search code examples
javaeclipsejunitclasspathclassloader

How can I see the classes on the java classpath at runtime in a non-maven project?


I have two projects with the same declared dependencies in eclipse. One set of unit tests work, and the other set does not. I am getting an error No tests matching [*methodname*]. Some googling suggests library issues, but I have not been able to identify where those could be getting introduced. The projects are almost identical and the test framework (junit, powermock, mockito) should be identical. Viewing the java build path in preferences -> java build path shows the same references. I'm suspecting that eclipse menus are not reflecting the actual classes being loaded at runtime. Is there a way to echo out the classpath at runtime so I can scan it for duplicates?

update: the underlying issue was that I had conflicting versions of junit and powermock on the classpath. I was able to resolve this by removing, re-adding, and re-ordering jars from the eclipse build path config panel. This was very tedious and the accepted solution below would have significantly reduced the resolution time.

this question was flagged as a duplicate, but the linked article is specific to maven, and doesn't address the underlying problem of seeing a classpath at runtime. the accepted solution is viable for maven and non-maven projects.


Solution

  • There are several ways of investigating the actual classpath at runtime:

    • Run your JVM with -verbose:class. This will produce output like so:

      [Loaded java.lang.Object from /Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib/rt.jar]
      [Loaded java.io.Serializable from /Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib/rt.jar]
      
    • Run the following code within your JVM:

      ClassLoader classloader = ClassLoader.getSystemClassLoader();
      
      URL[] urls = ((URLClassLoader) classloader).getURLs();
      
      for (URL url : urls) {
          System.out.println(url.getFile());
      }