Eclipse: Java Enum auto-completion of switch case

后端 未结 3 1673
遥遥无期
遥遥无期 2021-01-30 16:03

Is there a CTRL+space -like way of \"auto-constructing\" a switch case around a given Java Enum in Eclipse? I\'d like a stub with all Enum cases...

3条回答
  •  囚心锁ツ
    2021-01-30 16:33

    I don't know if it's possible to do this as a template, because the template would have to know which enum type you were using. But you could write a little script to print out the statement for you, and then just copy its output into your source file.

    public class SwitchWriter {
      public static void printSwitchStatement(String varName, Class E) {
        System.out.format("switch(%s) {\n", varName);
        for (Object o : E.getEnumConstants()) {
          System.out.format("case %s:\n  // TODO: Auto-generated switch statement stub\n  break;\n", o);
        }
        System.out.println("default:\n  // TODO: Auto-generated switch statement stub\n}");
      }
    }
    

    Output of SwitchWriter.printSwitchStatement("action", java.awt.Desktop.Action.class):

    switch(action) {
    case OPEN:
      // TODO: Auto-generated switch statement stub
      break;
    case EDIT:
      // TODO: Auto-generated switch statement stub
      break;
    case PRINT:
      // TODO: Auto-generated switch statement stub
      break;
    case MAIL:
      // TODO: Auto-generated switch statement stub
      break;
    case BROWSE:
      // TODO: Auto-generated switch statement stub
      break;
    default:
      // TODO: Auto-generated switch statement stub
    }
    

提交回复
热议问题