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

雨燕双飞 提交于 2019-11-27 11:51:00

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

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

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.

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
    }
}

You use the -Xlog option to configure or enable logging with the Java Virtual Machine (JVM) unified logging framework. The advantage is that you can write results to text file

Synopsis

-Xlog[:[what][:[output][:[decorators][:output-options [,...]]]]]

In Unified Logging syntax, -verbose:class equals -Xlog:class+load=info

For example

java -Xlog:class+load=info:classloaded.txt

Ocarle doc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!