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

前端 未结 13 1931
长情又很酷
长情又很酷 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:51

    I use org.reflections:

    Reflections reflections = new Reflections("com.mycompany");    
    Set> classes = reflections.getSubTypesOf(MyInterface.class);
    

    Another example:

    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        Reflections reflections = new Reflections("java.util");
        Set> classes = reflections.getSubTypesOf(java.util.List.class);
        for (Class aClass : classes) {
            System.out.println(aClass.getName());
            if(aClass == ArrayList.class) {
                List list = aClass.newInstance();
                list.add("test");
                System.out.println(list.getClass().getName() + ": " + list.size());
            }
        }
    }
    

提交回复
热议问题