How can I override the toString () method for all enum classes?

Is it possible to override the toString method for all Enum classes, and not override it only in the enum class. Example:

Coins.java:

 enum Coins { PENNY(1), POUND(100), NOTE(500); private int value; Coins(int coinValue) { value = coinValue; } [...] // Other code public String toString() { return name().charAt(0) + name().substring(1).toLowerCase(); } } 

DaysOfWeek.java:

 enum DaysOfWeek { MONDAY(1), TUESDAY(2), WEDNESDAY(3); private int dayID; DaysOfWeek(int ID) { dayID = ID; } [...] // Other code public String toString() { return name().charAt(0) + name().substring(1).toLowerCase(); } } 

Currently, I have to override toString() in every enum class. Can I create a generic toString method that will override all classes that have an enumeration type, without a toString entry in each class of type enum?

+5
source share
2 answers

No. You cannot override the Enum class, and you cannot make a subclass from which all your Enum inherit, since it is a language function with special rules . However, you can create a static helper method:

 public class Utils { public static String toEnumString(Enum<?> inputEnum) { return inputEnum.name().charAt(0) + inputEnum.name().substring(1).toLowerCase(); } } 

This can be used in two different ways:

  • You can still override toString() in your enumerations, but with a much lower probability of a copy error and the ability to change it each with one code change. eg.

     enum Coins { PENNY(1), POUND(100), NOTE(500); // snip public String toString() { return Utils.toEnumString(this); } } 
  • You can use it in other methods, for example:

     System.out.println(Utils.toEnumString(Coins.PENNY)); preparedStatement.setString(1, Utils.toEnumString(Coins.POUND)); 

You can also use Apache Commons or Google Guava to do the same if you want to add another library to your project:

+9
source

I would make a delegate / utlity / helper that will call all toString () enumeration methods. This avoids calling the utility class whenever you want to convert to a string.

 private static class CommonEnumToString { static String toString(Enum<?> e) { return e.name().charAt(0) + e.name().substring(1).toLowerCase(); } } 

Update toString () to call helper

 enum Coins { PENNY(1), POUND(100), NOTE(500); private int value; Coins(int coinValue) { value = coinValue; } public String toString() { return CommonEnumToString.toString(this); } } enum DaysOfWeek { MONDAY(1), TUESDAY(2), WEDNESDAY(3); private int dayID; DaysOfWeek(int ID) { dayID = ID; } public String toString() { return CommonEnumToString.toString(this); } } 

Test

 public static void main(String[] args) { System.out.println(DaysOfWeek.WEDNESDAY); // ==> Wednesday System.out.println(Coins.PENNY); // ==> Penny } 
+1
source

All Articles