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

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

    This is a tough problem and you will need to find out this information using static analysis, its not available easily at runtime. Basically get the classpath of your app and scan through the available classes and read the bytecode information of a class which class it inherits from. Note that a class Dog may not directly inherit from Animal but might inherit from Pet which is turn inherits from Animal,so you will need to keep track of that hierarchy.

提交回复
热议问题