简体   繁体   中英

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

I want to override toString() for my enum, Color . However, I can't figure out how to get the value of an instance of Color inside the Color enum. Is there a way to do this in Java?

Example:

public enum Color {
    RED,
    GREEN,
    BLUE,
    ...

    public String toString() {
        // return "R" for RED, "G", for GREEN, etc.
    }
}
public enum Color {
    RED("R"),
    GREEN("G"),
    BLUE("B");

    private final String str;
    private Color(String s){
        str = s;
    }
    @Override
    public String toString() {
        return str;
    }
}

You can use constructors for Enums. I haven't tested the syntax, but this is the idea.

You can also switch on the type of this , 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(); 
    } 
  } 
} 

Enum.name() - who'd of thunk it?

However, in most cases it makes more sense to keep any extra information in an instance variable that is set int the constructor.

Use super and String.substring() :

public enum Color
{
    RED,
    GREEN,
    BLUE;

    public String toString()
    {
        return "The color is " + super.toString().substring(0, 1);
    }
}

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

To do what you want you would do

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

What you might want to do instead is add an attribute called abbreviation and add it to the constructor, add a getAbbreviation() and use that instead of .toString()

I've found something like this (not tested tho):

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

}

Hope it helps a bit !

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM