Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 837
Yaneeve Avatar asked Apr 21 '10 08:04

Yaneeve


People also ask

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("");

Can you find all classes in a package using reflection?

If there are classes that get generated, or delivered remotely, you will not be able to discover those classes. The normal method is instead to somewhere register the classes you need access to in a file, or reference them in a different class. Or just use convention when it comes to naming.

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.

How can you directly access all classes in the package in Java?

Since Java enforces the most restrictive access, we have to explicitly declare packages using the export or open module declaration to get reflective access to the classes inside the module.


1 Answers

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); 
like image 111
bestsss Avatar answered Sep 23 '22 19:09

bestsss