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

后端 未结 12 1034
悲&欢浪女
悲&欢浪女 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:32

    The Enum Mapper project provides an an annotation processor which will make sure at compile-time that all enum constants are handled.
    Moreover it supports reverse lookup and paritial mappers.

    Usage example:

    @EnumMapper
    public enum Seasons {
      SPRING, SUMMER, FALL, WINTER
    }
    

    The annotation processor will generate a java class Seasons_MapperFull, which can be used to map all enum constants to arbitrary values.

    Here is an example use where we map each enum constant to a string.

    EnumMapperFull germanSeasons = Seasons_MapperFull
         .setSPRING("Fruehling")
         .setSUMMER("Sommer")
         .setFALL("Herbst")
         .setWINTER("Winter");
    

    You can now use the mapper to get the values, or do reverse lookup

    String germanSummer = germanSeasons.getValue(Seasons.SUMMER); // returns "Sommer"
    ExtremeSeasons.getEnumOrNull("Sommer");                 // returns the enum-constant SUMMER
    ExtremeSeasons.getEnumOrRaise("Fruehling");             // throws an IllegalArgumentException 
    

提交回复
热议问题