Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get which classes a ClassLoader has loaded?

I am trying to implement some unit testing for an old framework. I am attempting to mock out the database layer. Unfortunately our framework is a bit old and not quite using best practices so there is no clear separation of concerns. I am bit worried that trying to mock out the database layer might make the JVM load a huge number of classes that won't even be used.

I don't really understand class loaders that well so this might not be a problem. Is there a way to take a peak at all the classes a particular ClassLoader has loaded to prove what is going on under the hood?

like image 270
uriDium Avatar asked Sep 16 '09 10:09

uriDium


People also ask

How do I know what ClassLoader loads a class?

To know the ClassLoader that loads a class the getClassLoader() method is used. All classes are loaded based on their names and if any of these classes are not found then it returns a NoClassDefFoundError or ClassNotFoundException.

Where are JVM classes loaded?

The most straightforward approach for listing all classes loaded would be to log that in a console output or file. [Opened /Library/Java/JavaVirtualMachines/jdk1. 8.0_241. jdk/Contents/Home/jre/lib/rt.

What is class loader how many ClassLoader is there in Java?

As we can see, there are three different class loaders here: application, extension, and bootstrap (displayed as null). The application class loader loads the class where the example method is contained. An application or system class loader loads our own files in the classpath.

How do I get all classes in a classpath?

You can get all classpath roots by passing an empty String into ClassLoader#getResources() . Enumeration<URL> roots = classLoader. getResources("");


2 Answers

You can create your own Classloader and use that to load during the unit test. Have your own custom Classloader print out what it's doing.

Or if you just want to know which classes are loaded, do:

java -verbose:class
like image 177
Alex Miller Avatar answered Sep 21 '22 22:09

Alex Miller


Be warned that using

java -verbose

Will produce an enormous amount of output. Log the output to a file and then use grep. If you have the 'tee' filter you could try this:

java -verbose | tee classloader.log
grep class classloader.log
like image 32
Kelly S. French Avatar answered Sep 21 '22 22:09

Kelly S. French