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?
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()
.
Sample code that shows the idea of overriding toString:
public class Test {
enum Weather { Sunny, Cloudy;
@Override
public String toString() {
return "WEATHER." + super.toString().toUpperCase();
}
};
public static void main(String[] args) {
System.out.println(Weather.Sunny);
}
}
Output: WEATHER.SUNNY
There is no problem with defining enum that has a capitalized name. It would be not consistent with Java naming conventions, but it works.
enum WEATHER {
SUNNY, CLOUDY;
}
Then you would use like this:
WEATHER weather = WEATHER.SUNNY
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.