I am trying to list the order in which the Java class loader is loading my classes. if I use -verbose
parameter it will list every single interface/class it loads, including tons of interfaces such as Serializable, exceptions etc. Is there a way to tweak this output so it only shows which classes are loaded in the class my main method is defined?
Asked
Active
Viewed 1.1e+01k times
78

Alexander Oh
- 24,223
- 14
- 73
- 76

Bober02
- 15,034
- 31
- 92
- 178
3 Answers
80
I guess your best bet is to do the following:
- Output some fixed text once your
main
method starts and right before it ends. - Pipe the verbose output into a file
- Use things like less or grep to find the classes loaded between the two tags from the main method.
There's a similar question and some answers here: Is there a way to get which classes a ClassLoader has loaded?
Did you try -verbose:class
?
-
3In case anyone is wondering where this is documented: https://docs.oracle.com/en/java/javase/11/tools/java.html – Renato Jul 01 '21 at 13:30
19
Here's a sed expression that will parse the output of java -verbose:class to produce pairs of loaded class name and its jar file. You can further pipe through a sort to get unique jar files. For example,
java -verbose:class -version 2>/dev/null |
sed -ne 's/\[Loaded \(.\+\) from \(.\+\)\]/\2/p' |
sort -u
outputs
/usr/local/jdk1.7.0_67/jre/lib/rt.jar

Nicholas Sushkin
- 13,050
- 3
- 30
- 20
2
For Java 9+ you can do it with -Xlog:class+init
. E.g. this command prints the order of class loading when you start JVM:
java -Xlog:class+init -version
The command prints something like
[0.018s][info][class,init] 0 Initializing 'java/lang/Object'(no method) (0x0000000800000e60)
[0.018s][info][class,init] 1 Initializing 'java/lang/CharSequence'(no method) (0x0000000800009210)
[0.018s][info][class,init] 2 Initializing 'java/lang/String' (0x00000008000089b8)
[0.018s][info][class,init] 3 Initializing 'java/util/Comparator'(no method) (0x00000008000eb588)
[0.018s][info][class,init] 4 Initializing 'java/lang/String$CaseInsensitiveComparator'(no method) (0x000000080010dff8)
[0.018s][info][class,init] 5 Initializing 'java/lang/System' (0x0000000800002b68)
[0.019s][info][class,init] 6 Initializing 'java/lang/reflect/AnnotatedElement'(no method) (0x0000000800013cd0)
[0.019s][info][class,init] 7 Initializing 'java/lang/reflect/Type'(no method) (0x0000000800015210)
[0.019s][info][class,init] 8 Initializing 'java/lang/Class' (0x00000008000139e0)

Sergey Tsypanov
- 3,265
- 3
- 8
- 34