Why can't I use switch statement on a String?

前端 未结 16 2066
面向向阳花
面向向阳花 2020-11-21 07:57

Is this functionality going to be put into a later Java version?

Can someone explain why I can\'t do this, as in, the technical way Java\'s switch state

16条回答
  •  猫巷女王i
    2020-11-21 08:20

    For years we've been using a(n open source) preprocessor for this.

    //#switch(target)
    case "foo": code;
    //#end
    

    Preprocessed files are named Foo.jpp and get processed into Foo.java with an ant script.

    Advantage is it is processed into Java that runs on 1.0 (although typically we only supported back to 1.4). Also it was far easier to do this (lots of string switches) compared to fudging it with enums or other workarounds - code was a lot easier to read, maintain, and understand. IIRC (can't provide statistics or technical reasoning at this point) it was also faster than the natural Java equivalents.

    Disadvantages are you aren't editing Java so it's a bit more workflow (edit, process, compile/test) plus an IDE will link back to the Java which is a little convoluted (the switch becomes a series of if/else logic steps) and the switch case order is not maintained.

    I wouldn't recommend it for 1.7+ but it's useful if you want to program Java that targets earlier JVMs (since Joe public rarely has the latest installed).

    You can get it from SVN or browse the code online. You'll need EBuild to build it as-is.

提交回复
热议问题