How do I implement the following pseudocode in Java?
Object getInstance(Class<?> type)
{
switch (type)
{
case A.class:
return createA(param1, param2);
case B.class:
return createB(param3, param4, param5);
default:
throw new AssertionError("Unknown type: " + type);
}
}
I know I can probably implement this using a Map<Class<?>, Callable<Object>>
(mapping classes to a method that returns an object) but is there a more efficient/readable way to do this?
UPDATE: I'm sorry for the misleading pseudo code. I did not mean to imply that the classes have no-arg constructors. Each class is constructed differently. I know if-else works but it is not great from an efficiency point of view. It is O(n).