title: Create a dynamic class in java
body: <p>I'm working on a problem where different animal types implement the same talk() method from Animal interface.<br>
  If you look at <code>getAnimal()</code> method, you can see that, when a new kind of animal is added to the program, inside of that method has to be changed as well.<br>
  I want to add new animals just by subclassing Animal without changing anything in the already existing classes.<br>
  For example, add an animal "Dog", criteria="loyal"; talk="woof".<br>
  Could you tell me, how it is possible? Below is my code:</p>
  
  <pre><code>interface Animal {
  
      public void talk();
  }
  
  class Lion implements Animal {
  
      @Override
      public void talk() {
          System.out.println("ROARRRRR");
      }
  }
  
  class Mouse implements Animal {
  
      @Override
      public void talk() {
          System.out.println("SQUEEEEEAK");
      }
  }
  
  class Bison implements Animal {
  
      @Override
      public void talk() {
          System.out.println("BELLOWWWWW");
      }
  }
  
  class AnimalType {
  
      public static Animal getAnimal(String criteria) {
  
          // I refactor this method
          if (criteria.equals("small")) {
              return new Mouse();
          } else if (criteria.equals("big")) {
              return new Bison();
          } else if (criteria.equals("lazy")) {
              return new Lion();
          }
          return null;
      }
  }
  
  public class AnimalExamples {
  
      public static void main(String[] args) {
          AnimalType.getAnimal("small").talk();
          AnimalType.getAnimal("big").talk();
          AnimalType.getAnimal("lazy").talk();
  
          //  how to add an animal "Dog" here, criteria="loyal"; talk="woof"
          AnimalType.getAnimal("loyal").talk();
  
          try {
              AnimalType.getAnimal("small").talk();
          } catch (Exception ex) {
              System.out.println("Animal does not exists");
          }
      }
  }
  </code></pre>
  
  <p>I searched on google, understood it can be done by reflection. But do not know how. If possible, could you help me with this, please? Thanks in advance!</p>