title: Better way to instantiate multiple different classes in Java via factories
body: <p>Say you have a lot of similar classes that may get instantiated at any point. One obvious way to write this would be a whole slew of conditionals:</p>
  <pre><code>public static Common factory(String key, InstantiationObj instantiationObj) {
  
    if( key == &quot;A&quot;) {
      return new TypeA(instantiationObj);
    }
    else if( key == &quot;B&quot;) {
      return new TypeB(instantiationObj);
    }
    else if( key == &quot;C&quot; ) {
      return new TypeC(instantiationObj);
    } 
    else if( key == &quot;D&quot; ) {
      return new TypeD(instantiationObj);
    }
    else {
      return new DefaultClass(instantiationObj);
    }
  
  }
  </code></pre>
  <p>I like to avoid all the conditionals though. In Java I got this working:</p>
  <pre><code>public static &lt;T extends Common&gt; T factory(String key, InstantiationObj instantiationObj) throws Exception {  
    Class[] cArg = new Class[1];
    cArg[0] = InstantiationObj.class;
    HashMap&lt;String, Class&gt; potentialClasses = new HashMap&lt;&gt;();
    
    potentialClasses.put(&quot;A&quot;, TypeA.class);
    potentialClasses.put(&quot;B&quot;, TypeB.class);
    potentialClasses.put(&quot;C&quot;, TypeC.class);
    potentialClasses.put(&quot;D&quot;, TypeD.class);
  
    Class&lt;T&gt; classType = potentialClasses.getOrDefault(key, DefaultClass.class);
    return classType.getDeclaredConstructor(cArg).newInstance(instantiationObj);
  }
  </code></pre>
  <p>This is much easier to test, but it still looks clunky to me especially the block to determine the right constructor. Does Java have a more streamlined way of executing this pattern?</p>