title: Best way to call different classes at runtime in Java
body: <p>Let's imagine that we have to call one method from different classes by definition coming at run time. For example we receive JSON like this:</p>
  
  <pre><code>{"calculator": "MyClass1", "parameter1": 1.0, "parameter2": 2.0, ... }
  </code></pre>
  
  <p>MyClass1 and more classes either extend some base class or implement some interface (just to be able to enumerate them at run time). We have to create object, pass the parameters to the object and call calculate() method.</p>
  
  <p>I can think of two ways to do this:</p>
  
  <ol>
  <li><p>switch(calculatorString) { case "MyClass1": calculator = new MyClass1(); ...</p></li>
  <li><p>using Java Reflection</p></li>
  </ol>
  
  <p>The first way is really stupid because the code must be updated each time new calculator class is added to the project. The second way is slightly better, but the IDE is unable to catch any type errors we make while creating the objects and invoking the method.</p>
  
  <p>Are there other ways to do this (possibly better)?</p>