问题
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).
回答1:
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.
回答2:
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, ...]
回答3:
..? (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.
回答4:
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?
来源:https://stackoverflow.com/questions/7590495/method-to-dump-classes-on-the-classpath-from-inside-jvm