Note that there are some explanatory texts on larger screens.

plurals
  1. POAt runtime, find all classes in a Java application that extend a base class
    text
    copied!<p>I want to do something like this:</p> <pre><code>List&lt;Animal&gt; animals = new ArrayList&lt;Animal&gt;(); for( Class c: list_of_all_classes_available_to_my_app() ) if (c is Animal) animals.add( new c() ); </code></pre> <p>So, I want to look at all of the classes in my application's universe, and when I find one that descends from Animal, I want to create a new object of that type and add it to the list. This allows me to add functionality without having to update a list of things. I can avoid the following:</p> <pre><code>List&lt;Animal&gt; animals = new ArrayList&lt;Animal&gt;(); animals.add( new Dog() ); animals.add( new Cat() ); animals.add( new Donkey() ); ... </code></pre> <p>With the above approach, I can simply create a new class that extends Animal and it'll get picked up automatically.</p> <p>UPDATE: 10/16/2008 9:00 a.m. Pacific Standard Time:</p> <p>This question has generated a lot of great responses -- thank you. From the responses and my research, I've found that what I really want to do is just not possible under Java. There are approaches, such as ddimitrov's ServiceLoader mechanism that can work -- but they are very heavy for what I want, and I believe I simply move the problem from Java code to an external configuration file. </p> <p>Another way to state what I want: a static function in my Animal class finds and instantiates all classes that inherit from Animal -- without any further configuration/coding. If I have to configure, I might as well just instantiate them in the Animal class anyway. I understand that because a Java program is just a loose federation of .class files that that's just the way it is.</p> <p>Interestingly, it seems this is <a href="http://my.safaribooksonline.com/0596003390/csharpckbk-CHP-12-SECT-8" rel="noreferrer">fairly trivial</a> in C#.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload