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).
How about using the Class object to create a new instance?
private static final Set<Class> ALLOWED_CLASSES =
new HashSet<>(Arrays.asList(A.class, B.class));
Object getInstance(Class<?> type) {
if (!ALLOWED_CLASSES.contains(type)) {
throw new AssertionError("Unknown type: " + type);
}
return type.newInstance();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With