3

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.

Community
  • 1
  • 1
Paul Fournel
  • 10,807
  • 9
  • 40
  • 68

2 Answers2

4

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.

NiziL
  • 5,068
  • 23
  • 33
4

Extract the common code to the separate class:

class MetaEnumHelper {
   private String val;

   MetaEnumImpl(final v){
       val = v;
   }

   public String getDefaultValue() {
       return value;
   }

   public String getKey(MetaEnum metaEnum) {
        return (metaEnum.getClass().getPackage().getName() + "." + metaEnum.getClass().getSimpleName() + "." +
            metaEnum.toString()).toLowerCase();
   }
}

public enum A implements MetaEnum{
   ONE("1"), TWO("2");
   private MetaEnumHelper helper;
   A(final v){
       helper = new MetaEnumHelper(v);
   }
   @Override
   public String getDefaultValue() {
       return helper.getDefaultValue();
   }
   @Override
   public String getKey() {
        return helper.getKey(this);
   }
}

public enum B implements MetaEnum{
   UN("1"), DEUX("2");
   private MetaEnumHelper helper;
   B(final v){
       helper = new MetaEnumHelper(v);
   }
   @Override
   public String getDefaultValue() {
       return helper.getDefaultValue();
   }
   @Override
   public String getKey() {
       return helper.getKey(this);
   }
   ...other methods specific to this enum
}
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110