How to ensure completeness in an enum switch at compile time?

后端 未结 12 1028
悲&欢浪女
悲&欢浪女 2020-11-27 06:25

I have several switch statements which test an enum. All enum values must be handled in the switch statements by a case s

12条回答
  •  长情又很酷
    2020-11-27 06:33

    In Effective Java, Joshua Bloch recommends creating an abstract method which would be implemented for each constant. For example:

    enum Color {
        RED   { public String getName() {return "Red";} },
        GREEN { public String getName() {return "Green";} },
        BLUE  { public String getName() {return "Blue";} };
        public abstract String getName();
    }
    

    This would function as a safe switch, forcing you to implement the method if you add a new constant.

    EDIT: To clear up some confusion, here's the equivalent using a regular switch:

    enum Color {
        RED, GREEN, BLUE;
        public String getName() {
            switch(this) {
                case RED:   return "Red";
                case GREEN: return "Green";
                case BLUE:  return "Blue";
                default: return null;
            }
        }
    }
    

提交回复
热议问题