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

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

    Think about this from an aspect-oriented point of view; what you want to do, really, is know all the classes at runtime that HAVE extended the Animal class. (I think that's a slightly more accurate description of your problem than your title; otherwise, I don't think you have a runtime question.)

    So what I think you want is to create a constructor of your base class (Animal) which adds to your static array (I prefer ArrayLists, myself, but to each their own) the type of the current Class which is being instantiated.

    So, roughly;

    public abstract class Animal
        {
        private static ArrayList instantiatedDerivedTypes;
        public Animal() {
            Class derivedClass = this.getClass();
            if (!instantiatedDerivedClass.contains(derivedClass)) {
                instantiatedDerivedClass.Add(derivedClass);
            }
        }
    

    Of course, you'll need a static constructor on Animal to initialize instantiatedDerivedClass... I think this'll do what you probably want. Note that this is execution-path dependent; if you have a Dog class that derives from Animal that never gets invoked, you won't have it in your Animal Class list.

提交回复
热议问题