Using Enum values as String literals Using Enum values as String literals java java

Using Enum values as String literals


You can't. I think you have FOUR options here. All four offer a solution but with a slightly different approach...

Option One: use the built-in name() on an enum. This is perfectly fine if you don't need any special naming format.

    String name = Modes.mode1.name(); // Returns the name of this enum constant, exactly as declared in its enum declaration.

Option Two: add overriding properties to your enums if you want more control

public enum Modes {    mode1 ("Fancy Mode 1"),    mode2 ("Fancy Mode 2"),    mode3 ("Fancy Mode 3");    private final String name;           private Modes(String s) {        name = s;    }    public boolean equalsName(String otherName) {        // (otherName == null) check is not needed because name.equals(null) returns false         return name.equals(otherName);    }    public String toString() {       return this.name;    }}

Option Three: use static finals instead of enums:

public final class Modes {    public static final String MODE_1 = "Fancy Mode 1";    public static final String MODE_2 = "Fancy Mode 2";    public static final String MODE_3 = "Fancy Mode 3";    private Modes() { }}

Option Four: interfaces have every field public, static and final:

public interface Modes {    String MODE_1 = "Fancy Mode 1";    String MODE_2 = "Fancy Mode 2";    String MODE_3 = "Fancy Mode 3";  }


Every enum has both a name() and a valueOf(String) method. The former returns the string name of the enum, and the latter gives the enum value whose name is the string. Is this like what you're looking for?

String name = Modes.mode1.name();Modes mode = Modes.valueOf(name);

There's also a static valueOf(Class, String) on Enum itself, so you could also use:

Modes mode = Enum.valueOf(Modes.class, name);


You could override the toString() method for each enum value.

Example:

public enum Country {  DE {    @Override    public String toString() {      return "Germany";    }  },  IT {    @Override    public String toString() {      return "Italy";    }  },  US {    @Override    public String toString() {      return "United States";    }  }}

Usage:

public static void main(String[] args) {  System.out.println(Country.DE); // Germany  System.out.println(Country.IT); // Italy  System.out.println(Country.US); // United States}