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

前端 未结 13 1940
长情又很酷
长情又很酷 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条回答
  •  猫巷女王i
    2020-11-22 17:52

    The most robust mechanism for listing all subclasses of a given class is currently ClassGraph, because it handles the widest possible array of classpath specification mechanisms, including the new JPMS module system. (I am the author.)

    List> animals;
    try (ScanResult scanResult = new ClassGraph().whitelistPackages("com.zoo.animals")
            .enableClassInfo().scan()) {
        animals = scanResult
            .getSubclasses(Animal.class.getName())
            .loadClasses(Animal.class);
    }
    

提交回复
热议问题