title: At runtime, find all classes in a Java application that extend a base class
body: <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.  <s>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.</s> <strong>Update 5/10/19</strong> (11 years later!) There are now several libraries that can help with this according to @IvanNik's <a href="https://stackoverflow.com/a/9240969/9648">answer</a> <a href="https://github.com/ronmamo/reflections" rel="noreferrer">org.reflections</a> looks good. Also <a href="https://github.com/classgraph/classgraph" rel="noreferrer">ClassGraph</a> from @Luke Hutchison's <a href="https://stackoverflow.com/a/51625104/9648">answer</a> looks interesting. There are several more possibilities in the answers as well.</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>