L
lroland
Hi all
Due to a somewhat strange external requirement I need to ensure that
most of our enums can be treated as a single type that contains a
getDescription() method. Given the enum keyword is just syntactic
sugar for extending the Enum abstract class my initial idea was to do
something like this:
--
public interface EnumDescription<E extends Enum<E>> {
public String getDescription();
}
--
With the implementing enum ending up as
--
public enum Flag implements EnumDescription<Flag> {
ALL("All"), UNFLAGGED("Unflagged"), RED("Flagged with red flag"),
GREEN(
"Flagged with green flag"), BLUE("Flagged with blue flag");
private String description;
Flag(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
--
Which of cause looses all the enum type information - i.e. the
following will not work because "ordinal" does not exists in the
interface.
--
public static void main(String[] args) {
// full enums
Flag[] flags = Flag.values();
// print description and ordinal
String s = new String();
for (EnumDescription<?> d : flags) {
s += " '" + d.getDescription() + " (id: " + d.ordinal() + ")' ";
}
System.out.println(s);
}
--
Given i also need the other enum methods (valueOf...) it does not
seams like a sensible solution to just add then to the interface
(valueOf is also static which creates its own set of problems). So
basically I need a way to keep the type information from Enum in my
new type - is this even possible ?.
Due to a somewhat strange external requirement I need to ensure that
most of our enums can be treated as a single type that contains a
getDescription() method. Given the enum keyword is just syntactic
sugar for extending the Enum abstract class my initial idea was to do
something like this:
--
public interface EnumDescription<E extends Enum<E>> {
public String getDescription();
}
--
With the implementing enum ending up as
--
public enum Flag implements EnumDescription<Flag> {
ALL("All"), UNFLAGGED("Unflagged"), RED("Flagged with red flag"),
GREEN(
"Flagged with green flag"), BLUE("Flagged with blue flag");
private String description;
Flag(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
--
Which of cause looses all the enum type information - i.e. the
following will not work because "ordinal" does not exists in the
interface.
--
public static void main(String[] args) {
// full enums
Flag[] flags = Flag.values();
// print description and ordinal
String s = new String();
for (EnumDescription<?> d : flags) {
s += " '" + d.getDescription() + " (id: " + d.ordinal() + ")' ";
}
System.out.println(s);
}
--
Given i also need the other enum methods (valueOf...) it does not
seams like a sensible solution to just add then to the interface
(valueOf is also static which creates its own set of problems). So
basically I need a way to keep the type information from Enum in my
new type - is this even possible ?.