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

前端 未结 13 1937
长情又很酷
长情又很酷 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 18:01

    One way is to make the classes use a static initializers... I don't think these are inherited (it won't work if they are):

    public class Dog extends Animal{
    
    static
    {
       Animal a = new Dog();
       //add a to the List
    }
    

    It requires you to add this code to all of the classes involved. But it avoids having a big ugly loop somewhere, testing every class searching for children of Animal.

提交回复
热议问题