Is it possible to override the method toString
for all Enum
classes, rather than overriding it only in the enum class. Example:
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();
}
}
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 each enum class. Can I create a generic toString
method that will override all classes that are of enum type without actually writing toString
in every enum type class?
No. You can't override the system's Enum
class, and you cannot make a subclass from which all of your Enum
s inherit from as it is a language feature with a lot of special rules. However, you can make 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 enums, but with a lot less chance for copy paste error, and the ability to change it everyone with one code change. e.g.
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 thing, if you want to add another library to your project:
WordUtils.capitalizeFully
CaseFormat.UpperCamel
I'd make a delegate/utlity/helper that all the enum toString() methods call. This avoids having to call a utility class whenever you wish 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 the toString() to call the 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With