16

Is there a template or something for generating a switch statement for Java enum in Eclipse?

So that when I got an enum and I want to have a switch with all the values, I didn't have to write all it myself?

Touko
  • 11,359
  • 16
  • 75
  • 105
  • 1
    Not answering your question but you may want to consider the “replace switch with polymorphism” refactoring. – CurtainDog May 15 '09 at 12:38
  • 1
    See http://stackoverflow.com/questions/859563/java-enums-and-switch-statements-the-default-case for a better way than using switch. In short visitor pattern. – KitsuneYMG May 15 '09 at 12:45
  • 3
    As a note to the above two comments, there are plenty of situations where switch on an enum is valid. If the enum is being used as a "type code", polymorphism is likely a better option. If the enum represents states, then the link kts points out is useful (the answer in there is basically the GoF state pattern implemented in an enum) – Scott Stanchfield May 15 '09 at 14:06

2 Answers2

19

There certainly is, at least in 3.5.

Starting with something like this:

switch(a.getType()){

}

All you need to do is click on the switch keyword and hit CTRL+1. You should get a drop down which includes the option "Add missing case statements"

Peter Recore
  • 14,037
  • 4
  • 42
  • 62
  • Nice, thanks. And in addition to this, using Ctrl-1 suggestions also with other cases than plain problems is a good thing to know. – Touko Dec 30 '09 at 11:02
  • 1
    +1. Note that if "Enum type constant not covered on 'switch'" is set to generate a warning/error, CTRL+1 on that line does not work. You have to select the `switch` keyword and then press CTRL+1. – Ionuț G. Stan Jul 19 '11 at 10:56
1

The content assists in Eclipse 3.4 will help you write the code. Just type case and press Ctrl+Space and you'll get a list of unused enums.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • Yes, but then I still got to write each one separately even though the completion speeds the process up. – Touko May 15 '09 at 12:26
  • 2
    you may try out http://3pintech.com/products/fast-code/templates.htm#createswitchcaseenum..with this one can generate switch-case/if-else-if structure of specific enum. This plugin has many other useful features, you may have a look at http://3pintech.com/products.htm. – Krishnaveni May 10 '13 at 03:52