开发者

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).


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, ...]


..? (Ideally some Java code)

If you were looking only to resolve a Class-Not-Found bug, then adding a dump code within the app can add complexity to turn it off later. Perhaps it would be better to use -verbose:class JVM argument which would output all classes loaded at runtime. Its easy to turn off and output of the console can be easily redirected to a log.


That's actually not what you want to see if you're getting a CNFE, since it's not found. Plus not all available classes will be loaded at any given time.

Start by going through this list. But in general, if it's not found, it's actually not found.


Well, you could create a memory dump (e.g. via jmap) and view it (e.g. via jhat).

Alternatively, IIRC jconsole can show the loaded classes, so you could just view them. I'm not entirely sure though and I don't have a running jconsole right now.

A third alternative (for Java 5+) would be VisualVM which is part of the Java6+ distribution.

However, most certainly your jar file is not on the classpath or you are using some custom classloaders. Could you elaborate on how you put that jar on the classpath?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜