In Java, how do I get the enum value inside the enum itself?

I want to override toString() for my enum, Color . However, I cannot figure out how to get the value of the Color instance inside the Color enumeration. Is there any way to do this in Java?

Example:

 public enum Color { RED, GREEN, BLUE, ... public String toString() { // return "R" for RED, "G", for GREEN, etc. } } 
+4
source share
6 answers
 public enum Color { RED("R"), GREEN("G"), BLUE("B"); private final String str; private Color(String s){ str = s; } public String toString() { return str; } } 

You can use constructors for Enums. I have not tested the syntax, but this is an idea.

+16
source

You can also include this type, for example:

 public enum Foo { A, B, C, D ; @Override public String toString() { switch (this) { case A: return "AYE"; case B: return "BEE"; case C: return "SEE"; case D: return "DEE"; default: throw new IllegalStateException(); } } } 
+11
source

Enum.name() - who would say that?

However, in most cases, it makes sense to store additional information in the instance variable that is specified in the constructor.

+4
source

Use super and String.substring() :

 public enum Color { RED, GREEN, BLUE; public String toString() { return "The color is " + super.toString().substring(0, 1); } } 
+2
source

Java does this for you by default, it returns .name () in .toString (), you only need to override toString () if you need something different from the name. Interesting methods are: .name () and .ordinal () and .valueOf ().

To do what you want, do

 .toString(this.name().substring(1)); 

Instead, you can add an attribute with the abbreviation and add it to the constructor, add getAbbreviation () and use this instead of .toString ()

0
source

I found something like this (not verified by tho):

 public enum Color { RED{ public String toString() { return "this is red"; } }, GREEN{ public String toString() { return "this is green"; } }, ... 

}

Hope this helps a bit!

0
source

Source: https://habr.com/ru/post/1302168/


All Articles