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

纵然是瞬间 提交于 2019-12-17 10:33:49

问题


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?


回答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



回答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



回答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.




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


来源:https://stackoverflow.com/questions/1432180/is-there-a-way-to-get-which-classes-a-classloader-has-loaded

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