Override the value ofof () and toString () in a Java enumeration

The values ​​in my enum are words that must have spaces in them, but enumerations cannot have spaces in their meanings, so they are all grouped. I want to override toString() to add these spaces where I say.

I also want the enum to provide the correct enum when I use valueOf() on the same line where I added the spaces.

For example:

 public enum RandomEnum { StartHere, StopHere } 

Call toString() on RandomEnum , the value of which StartHere returns the string "Start Here" . Calling valueOf() on the same line ( "Start Here" ) returns the value of the StartHere enumeration.

How can i do this?

+86
java tostring override enums
Mar 12 2018-12-12T00:
source share
7 answers

You can try this code. Since you cannot override the valueOf method, you must define your own method ( getEnum in the sample code below) that returns the desired value and changes your client to use this method instead.

 public enum RandomEnum { StartHere("Start Here"), StopHere("Stop Here"); private String value; RandomEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return this.getValue(); } public static RandomEnum getEnum(String value) { for(RandomEnum v : values()) if(v.getValue().equalsIgnoreCase(value)) return v; throw new IllegalArgumentException(); } } 
+144
Mar 12 2018-12-12T00:
source share

Try this, but I'm not sure it will work anywhere :)

 public enum MyEnum { A("Start There"), B("Start Here"); MyEnum(String name) { try { Field fieldName = getClass().getSuperclass().getDeclaredField("name"); fieldName.setAccessible(true); fieldName.set(this, name); fieldName.setAccessible(false); } catch (Exception e) {} } } 
+18
Feb 20 '14 at 9:21
source share

You can use a static map in your enum, which displays strings for enum constants. Use it in the static getEnum method. This skips the need to iterate through enumerations every time you want to get one of its String values.

 public enum RandomEnum { StartHere("Start Here"), StopHere("Stop Here"); private final String strVal; private RandomEnum(String strVal) { this.strVal = strVal; } public static RandomEnum getEnum(String strVal) { if(!strValMap.containsKey(strVal)) { throw new IllegalArgumentException("Unknown String Value: " + strVal); } return strValMap.get(strVal); } private static final Map<String, RandomEnum> strValMap; static { final Map<String, RandomEnum> tmpMap = Maps.newHashMap(); for(final RandomEnum en : RandomEnum.values()) { tmpMap.put(en.strVal, en); } strValMap = ImmutableMap.copyOf(tmpMap); } @Override public String toString() { return strVal; } } 

Just make sure that the static map initialization occurs below the declaration of the listing constants.

BTW - type "ImmutableMap" - is Google guava API, and I definitely recommend it in such cases.




EDIT - for comments:

  • This solution assumes that each assigned string value is unique and non-empty. Given that the creator of enum can handle this, and that the string matches the unique and non-zero value of the enumeration, this seems like a safe constraint.
  • I added the toSTring () method asked in the question
+8
Nov 26 '12 at 20:17
source share

How about a Java 8 implementation? (zero can be replaced by your default Enum)

 public static RandomEnum getEnum(String value) { List<RandomEnum> list = Arrays.asList(RandomEnum.values()); return list.stream().filter(m -> m.value.equals(value)).findAny().orElse(null); } 

Or you could use:

 ...findAny().orElseThrow(NotFoundException::new); 
+8
Oct 06 '15 at 16:49
source share

I do not think that you are going to work with valueOf ("Start here"). But as for spaces ... try the following ...

 static private enum RandomEnum { R("Start There"), G("Start Here"); String value; RandomEnum(String s) { value = s; } } System.out.println(RandomEnum.G.value); System.out.println(RandomEnum.valueOf("G").value); Start Here Start Here 
+2
Mar 12 '12 at 6:00
source share

Below is a nice universal alternative to valueOf ()

 public static RandomEnum getEnum(String value) { for (RandomEnum re : RandomEnum.values()) { if (re.description.compareTo(value) == 0) { return re; } } throw new IllegalArgumentException("Invalid RandomEnum value: " + value); } 
+2
Jun 27 '12 at 9:20
source share

You still have the opportunity to implement the following in your enumeration:

 public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name){...} 
+1
Nov 24 '17 at 17:16
source share



All Articles