Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we switch on classes in Java 7+?

It seems to me that such a switch statement would make a lot of sense, but it gives a compile error :

public void m(Class c) {
   switch (c) {
       case SubClassOfC1.class : //do stuff; break;
       case SubClassOfC2.class : //do stuff; break;
   }
} 

However, classes are not supported to switch on. What is the reason why?

I am not trying to workaround instanceof, it's really at the class level that I got some operations to perform, no instances there.

The compile error is around SubClassOfC1 & SubClassOfC2 : constant expression required.

like image 952
Snicolas Avatar asked Jul 27 '15 22:07

Snicolas


2 Answers

It's because we can only switch on Constant Expressions (§15.28) or Enum constants (§8.9.1).

From the JLS:

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.

To imagine why this might be, think about the optimization that occurs when the Java compiler is attempting to compile a switch statement.

  • It wants to absolutely, positively guarantee equality
  • It wants to be able to maximize performance (branch prediction) for all the cases
  • It wants to have an effective, consistent way of transforming the constant expressions into an integer lookup table (this is why long and float and double are not supported, but String is).

Note that String being supported in switch statements was added only in Java 7. This is because the compiler uses a behind the scenes conversion of switch String to switch int, as detailed in this article. Quick summary:

This code:

public class StringInSwitchCase {
    public static void main(String[] args) {
        String mode = args[0];
        switch (mode) {
        case "ACTIVE":
            System.out.println("Application is running on Active mode");
            break;
        case "PASSIVE":
            System.out.println("Application is running on Passive mode");
            break;
        case "SAFE":
            System.out.println("Application is running on Safe mode");
        }
    }
}

Becomes this code:

public class StringInSwitchCase {
    public StringInSwitchCase() {}

    public static void main(string args[]) {
        String mode = args[0];
        String s;
        switch ((s = mode).hashCode()) {
        default:
            break;
        case -74056953:
            if (s.equals("PASSIVE")) {
                System.out.println("Application is running on Passive mode");
            }
            break;
        case 2537357:
            if (s.equals("SAFE")) {
                System.out.println("Application is running on Safe mode");
            }
            break;
        case 1925346054:
            if (s.equals("ACTIVE")) {
                System.out.println("Application is running on Active mode");
            }
            break;
        }
    }
}

We can't reliably turn Class objects into ints the same way. Class doesn't override hashCode, it uses System.identityHashCode.

Note also that the same class is not always the same Class, if it has been loaded with a different ClassLoader.

like image 126
durron597 Avatar answered Sep 28 '22 17:09

durron597


Interestingly, all answers so far are basically saying “because the specification says so”, which is correct but not really satisfying. Before Java 7, Strings were not allowed and that was often treated like being carved in stone.

But technical obstacles shouldn’t drive language design. If there is no way to compile it to efficient code, it might still get compiled to the equivalent of if … else … clauses, and still have a win on source code brevity. In the case of String values, there is an efficient way. Just switch over the invariant hashcode and perform an equals check on the match candidate. In fact, the specification does not mandate to use the hash code, it could be any invariant int property, e.g. the length or the first character, but it’s value should be different for each String.

Similarly, a switch over Class objects is possible. It’s hash code is not guaranteed to be the same, but each class has a constant name with a constant hash code. E.g. the following works:

public class ClassSwitch {
    static final class Foo {}
    static final class Bar {}
    static final class Baz {}

    public static void main(String... arg) {
        Class<?> cl=Bar.class;
        switch(cl.getSimpleName().hashCode()) {
            case 70822: 
                if(cl==Foo.class) {
                    System.out.println("case Foo:");
                }
                break;
            case 66547: 
                if(cl==Bar.class) {
                    System.out.println("case Baz:");
                }
                break;
            case 66555: 
                if(cl==Baz.class) {
                    System.out.println("case Baz:");
                }
                break;
        }
    }
}

I used the simple name instead of the qualified name, so that this example code is package independent. But I think, the picture is clear. It is possible to implement efficient switch statements for any kind of object which has a constant int property that can be predicted at compile time. That said, there is also no reason not to support long switches. There are plenty of ways to calculate a suitable int from a long


So there are another important decisions to make.

Is this feature really a benefit? It looks like code smell—even the addition of String support was controversial. It does not add new possibilities as you may do the same with if-else for a small number of classes or a HashMap<Class,SomeHandlerType> for bigger numbers. And it doesn’t really look like something that is needed so often, that it is worth expanding the language specification, even if it is just a single sentence that has to be added.

These are the considerations that drive the language design, but it’s not that minds and balances cannot change. So I’m not saying that’s impossible that a future version gets this feature.

But well, looking at the quality of generated String switch code I’d rather code my switches manually…

like image 24
Holger Avatar answered Sep 28 '22 16:09

Holger