javaidentifierenumerators

Java - create enums with dot notation


I need to have enums with dot notation like this WEATHER.SUNNY since they represent topics using wildcards. I know that this is not possible because enums need to be valid identifiers.

here someone suggest to overwrite the toString method but I dont really get how that is meant. However, is it still possible to do so?


Solution

  • You can definitely do what @Stefan suggests, but this might be a good use case for attaching a field to your enum values:

    public enum Topic {
        SUNNY("WEATHER.SUNNY"), CLOUDY("WEATHER.CLOUD"), ...
    
        String notation;
    
        Topic(String notation) {
            this.notation = notation;
        }
    
        public String getNotation() { return notation; }
    }
    

    And then you can invoke Topic.SUNNY.getNotation().