jeudi 27 septembre 2018

Best way to call different classes at runtime in Java

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:

{"calculator": "MyClass1", "parameter1": 1.0, "parameter2": 2.0, ... }

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.

I can think of two ways to do this:

  1. switch(calculatorString) { case "MyClass1": calculator = new MyClass1(); ...

  2. using Java Reflection

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.

Are there other ways to do this (possibly better)?





Aucun commentaire:

Enregistrer un commentaire