I have two Enums implementing the same interface
public interface MetaEnum{
String getDefaultValue();
String getKey();
}
public enum A implements MetaEnum{
ONE("1"), TWO("2");
private String val;
A(final v){
val = v;
}
@Override
public String getDefaultValue() {
return value;
}
@Override
public String getKey() {
return (this.getClass().getPackage().getName() + "." + this.getClass().getSimpleName() + "." +
this.toString()).toLowerCase();
}
}
public enum B implements MetaEnum{
UN("1"), DEUX("2");
private String val;
B(final v){
val = v;
}
@Override
public String getDefaultValue() {
return value;
}
@Override
public String getKey() {
return (this.getClass().getPackage().getName() + "." + this.getClass().getSimpleName() + "." +
this.toString()).toLowerCase();
}
...other methods specific to this enum
}
I have duplicated code and I would like to avoid it. Is there a way to implement getKey in a sort of abstract class? I looked at this question Java Enum as generic type in Enum but it cannot adapt it to what I need.
The default method from Java 8 should help you :)
This feature allows you to implement method inside an interface.
public interface MetaEnum {
String getValue();
default String getKey() {
return (this.getClass().getPackage().getName() + "." +
this.getClass().getSimpleName() + "." +
this.toString()).toLowerCase();
}
}
Unfortunately, you can't implement a default method for getters, so you still have some duplicate code.
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