Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to implement switch on Class?

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).

like image 350
Gili Avatar asked Dec 04 '25 08:12

Gili


1 Answers

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();
}
like image 88
Mureinik Avatar answered Dec 05 '25 23:12

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!