Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible use a class name in java switch/case statement? [duplicate]

I would like to use a java switch statement, which uses class names as case constants. Is it possible somehow? Or do I have to duplicate the class names?

Following code does not work because of compiler error:

case expressions must be constant expressions

String tableName = "MyClass1";

...

switch (tableName) {
case MyClass1.class.getSimpleName():
    return 1;
case MyClass2.class.getSimpleName():
    return 2;
default:
    return Integer.MAX_VALUE;
}

Here is a online demonstration of the issue (openjdk 1.8.0_45): http://goo.gl/KvsR6u

like image 889
dedek Avatar asked Jan 05 '16 13:01

dedek


People also ask

Can we use duplicate switch case in Java?

Two case labels in a switch statement cannot be the same. The code would not compile because case label 10 is repeated.

Are double data type allowed in switch case?

The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed.

Can switch case use char in Java?

The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.


1 Answers

The compiler error already says it. The case labels must be constant expressions and neither, class literals nor the result of invoking getSimpleName() on them, are constant expressions.

A working solution would be:

String tableName = "MyClass1";
...
switch (tableName) {
    case "MyClass1":
        return 1;
    case "MyClass2":
        return 2;
    default:
        return Integer.MAX_VALUE;
}

The expression MyClass1.class.getSimpleName() is not simpler than "MyClass1", but, of course, there won’t be any compile-time check whether the names match existing classes and refactoring tools or obfuscators don’t notice the relationship between the class MyClass1 and the string literal "MyClass1".

There is no solution to that. The only thing you can do to reduce the problem, is to declare the keys within the associated class to document a relationship, e.g.

class MyClass1 {
    static final String IDENTIFIER = "MyClass1";
    ...
}
class MyClass2 {
    static final String IDENTIFIER = "MyClass2";
    ...
}
...
String tableName = MyClass1.IDENTIFIER;
...
switch (tableName) {
    case MyClass1.IDENTIFIER:
        return 1;
    case MyClass2.IDENTIFIER:
        return 2;
    default:
        return Integer.MAX_VALUE;
}

This documents the relationship to the reader, but tools still won’t ensure that the actual string contents matches the class name. However, depending on what you want to achieve, it might become irrelevant now, whether the string contents matches the class name…

like image 184
Holger Avatar answered Oct 14 '22 01:10

Holger