javaswitch-statement

Why isn't it possible to switch over class objects?


Why isn't it possible to switch over different classes in Java? Every class-instance exists only once and is an immutable constant.

static void switchOnClass(Class<?> cls) {
    switch (cls) {
    case String.class -> System.out.println("String class");
    case Integer.class -> System.out.println("Integer class");
    default -> System.out.println("Unknown");
    }
}

Solution

  • To answer my own question: The use case seems to be not common enough, that this feature is supported. Currently (as of Java 18) a switch-case-statement supports switching over literals:

    It can utilize (exhaustive) pattern-matching like the instanceof operator, and as of Java 19 it will support record-pattern-matching which will maybe get extended by the following:

    Future Work

    There are many directions in which the record patterns described here could be extended:

    • Array patterns, whose subpatterns match individual array elements;
    • Varargs patterns, when the record is a varargs record;
    • Inference for type arguments in generic record patterns, possibly using a diamond form (<>);
    • Do-not-care patterns, which can appear as an element in a record component pattern list but do not declare a pattern variable; and
    • Patterns based upon arbitrary classes rather than only record classes.

    But currently it seems the best way to switch over classes would be, like @Davide pointed out, to use a uniquely identifieable, human-readable attribute, like their name/path. Which in itself would be restricted by anonymous, hidden, and local classes.