I have 2 or more enums with the same methods in each. I need to use all these enums to validate a message in another class. Each enum have the same methods. I understand how to pass an enum as a generic parameter but I don't believe it is then possible to call that enum's method in the method that receives the enum as a generic enum.
-
1Share some codeazro– azro2018-02-21 08:26:30 +00:00Commented Feb 21, 2018 at 8:26
-
7Use interfaces. Enums can implement interfaces.Erwin Bolwidt– Erwin Bolwidt2018-02-21 08:26:52 +00:00Commented Feb 21, 2018 at 8:26
-
2Why would an Enum implement an Interface?Erwin Bolwidt– Erwin Bolwidt2018-02-21 08:28:05 +00:00Commented Feb 21, 2018 at 8:28
Add a comment
|
1 Answer
Just like other classes, enums can implement interfaces.
interface CanThing {
void doThing();
}
enum Validate implements CanThing {
ONE_THING {
@Override
public void doThing() {
System.out.println("One thing");
}
},
OTHER_THING;
// Default.
@Override
public void doThing() {
System.out.println("No thing");
}
}
public void doAThing(CanThing thing) {
thing.doThing();
}
public void test(String[] args) {
for (CanThing t: Validate.values()) {
doAThing(t);
}
}