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

29,631

Solution 1

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

Solution 2

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

Solution 3

I am not sure. But there is one way I see it could be done. It maybe overrly ridiculous though. You can try aspects and put a pointcut for loadclass. Also maybe the jvm argument -verbose maybe helpful.

Solution 4

As an alternative way, for a particular Class-loader as you mentioned, you can use this code snippet. Just change value of obj variable if you want.

Object obj = this;
ClassLoader classLoader = obj.getClass().getClassLoader();
File file = new File("classloderClasses.txt");
if (file.exists()) {
    file.delete();
}
if (classLoader != null) {
    try {
        Class clClass = classLoader.getClass();
        while (clClass != ClassLoader.class) {
            clClass = clClass.getSuperclass();
        }
        java.lang.reflect.Field classesField = clClass.getDeclaredField("classes");
        classesField.setAccessible(true);
        Vector classes = (Vector) classesField.get(classLoader);
        FileOutputStream fos = new FileOutputStream("classloderClasses.txt", true);
        fos.write(("******************** " + classLoader.toString() + " ******************** " + "\n").getBytes());
        fos.write(Arrays.toString(classes.toArray()).getBytes());
        fos.close();
    } catch (Exception exception) {
        exception.printStackTrace();
        // TODO
    }
}
Share:
29,631
uriDium
Author by

uriDium

Comp Sci Honours Java Developer Freelance ASP.Net developer

Updated on July 19, 2022

Comments

  • uriDium
    uriDium almost 2 years

    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?