How can I list all classes loaded in a specific class loader

Yaneeve picture Yaneeve · Apr 21, 2010 · Viewed 49.8k times · Source

For debug reasons, and curiosity, I wish to list all classes loaded to a specific class loader.

Seeing as most methods of a class loader are protected, what is the best way to accomplish what I want?

Thanks!

Answer

bestsss picture bestsss · Apr 21, 2012

Try this. It's a hackerish solution but it will do.

The field classes in any classloader (under Sun's impl since 1.0) holds hard reference to the classes defined by the loader so they won't be GC'd. You can take a benefit from via reflection.

Field f = ClassLoader.class.getDeclaredField("classes");
f.setAccessible(true);

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Vector<Class> classes =  (Vector<Class>) f.get(classLoader);