I currently use an enum defined as such :
public enum Language{
English("english", "eng", "en", "en_GB", "en_US"),
German("german", "de", "ge"),
Croatian("croatian", "hr", "cro"),
Russian("russian");
private final List<String> values;
Language(String ...values) {
this.values = Arrays.asList(values);
}
public List<String> getValues() {
return values;
}
public static Language find(String name) {
for (Language lang : Language.values()) {
if (lang.getValues().contains(name)) {
return lang;
}
}
return null;
}
}
Thing is, I will have to use several enums using the same methods and constructor. The only thing changing would in my case be the values of the enum itself.
Is there a way for me to create a superclass of this enum that I could reuse ?
So that I could do something like :
public Language extends(specializedEnum){
English("english", "eng", "en", "en_GB", "en_US"),
German("german", "de", "ge"),
Croatian("croatian", "hr", "cro"),
Russian("russian");
}
Thank you by advance !
There are difficulties with this in Java, but a solution that will give you a good deal of what you need is to make all your enums implement a common interface.
You’ll have trouble reusing the code for the methods that implement the interface, but you can mitigate the damage by delegating the real work to outside methods.
Also, often a lookup-by-name function will be needed that gives you the right enum member regardless of the exact
enumclass. This can be accomplished using a separateHashMapthat aggregates all enum members.Basically, this is the outline of how I’m doing it in a project right now.