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

前端 未结 5 1905
故里飘歌
故里飘歌 2020-12-30 13:35

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 S         


        
5条回答
  •  时光取名叫无心
    2020-12-30 14:02

    Well, according to the documentation, switch only supports a limited set of data types:

    A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer

    My guess at why this is the case: because it would be difficult for the compiler to generate efficient code to switch on something else than a relatively simple data type.

提交回复
热议问题