At runtime, find all classes in a Java application that extend a base class

前端 未结 13 1876
长情又很酷
长情又很酷 2020-11-22 17:25

I want to do something like this:

List animals = new ArrayList();

for( Class c: list_of_all_classes_available_to_my_app() )
   i         


        
13条回答
  •  遥遥无期
    2020-11-22 17:58

    You could use ResolverUtil (raw source) from the Stripes Framework
    if you need something simple and quick without refactoring any existing code.

    Here's a simple example not having loaded any of the classes:

    package test;
    
    import java.util.Set;
    import net.sourceforge.stripes.util.ResolverUtil;
    
    public class BaseClassTest {
        public static void main(String[] args) throws Exception {
            ResolverUtil resolver = new ResolverUtil();
            resolver.findImplementations(Animal.class, "test");
            Set> classes = resolver.getClasses();
    
            for (Class clazz : classes) {
                System.out.println(clazz);
            }
        }
    }
    
    class Animal {}
    class Dog extends Animal {}
    class Cat extends Animal {}
    class Donkey extends Animal {}
    

    This also works in an application server as well since that's where it was designed to work ;)

    The code basically does the following:

    • iterate over all the resources in the package(s) you specify
    • keep only the resources ending in .class
    • Load those classes using ClassLoader#loadClass(String fullyQualifiedName)
    • Checks if Animal.class.isAssignableFrom(loadedClass);

提交回复
热议问题