Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to dump classes on the classpath from inside JVM?

My code is failing with a ClassNotFoundException.

I can see that the jar file containing the class is definitely on the classpath from the command prompt execution.

Is there a way to dump the list of classes on the classpath from the JVM? (Ideally some Java code).

(I don't want to see the classes in a directory, I want to see a list of what is loaded into the JVM).

like image 283
hawkeye Avatar asked Dec 01 '22 07:12

hawkeye


1 Answers

You can programatically display the classpath by looking at the classloaders and dumping the URLs they are loading from.

Something like this:

import java.net.URLClassLoader;
import java.util.Arrays;

public class ClasspathDumper
{
    public static void main(String... args)
    {
        dumpClasspath(ClasspathDumper.class.getClassLoader());
    }

    public static void dumpClasspath(ClassLoader loader)
    {
        System.out.println("Classloader " + loader + ":");

        if (loader instanceof URLClassLoader)
        {
            URLClassLoader ucl = (URLClassLoader)loader;
            System.out.println("\t" + Arrays.toString(ucl.getURLs()));
        }
        else
            System.out.println("\t(cannot display components as not a URLClassLoader)");

        if (loader.getParent() != null)
            dumpClasspath(loader.getParent());
    }
}

it would produce output similar to:

Classloader sun.misc.Launcher$AppClassLoader@2a340e:
    [file:/C:/Java/workspaces/myproject/bin/]
Classloader sun.misc.Launcher$ExtClassLoader@bfbdb0:
    [file:/C:/Java/jdk/jdk1.7.0/jre/lib/ext/dnsns.jar, file:/C:/Java/jdk/jdk1.7.0/jre/lib/ext/localedata.jar, file:/C:/Java/jdk/jdk1.7.0/jre/lib/ext/sunec.jar, file:/C:/Java/jdk/jdk1.7.0/jre/lib/ext/sunjce_provider.jar, ...]
like image 144
prunge Avatar answered Dec 10 '22 13:12

prunge