Java 实现相同接口的两个枚举共享一个方法

Java 实现相同接口的两个枚举共享一个方法,java,enums,Java,Enums,我有两个枚举实现相同的接口 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 getDefau

我有两个枚举实现相同的接口

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
}      
我有重复的代码,我想避免它。有没有办法在一种抽象类中实现getKey?我看了这个问题,但它不能适应我的需要。

Java 8中的默认方法应该可以帮助您:)
此功能允许您在接口内实现方法

public interface MetaEnum {
  String getValue();  

  default String getKey() {
    return (this.getClass().getPackage().getName() + "." + 
            this.getClass().getSimpleName() + "." +
            this.toString()).toLowerCase();
  }
}

不幸的是,您无法为getter实现
默认方法,因此仍然有一些重复的代码。

将公共代码提取到单独的类:

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
}

你会用Java8吗<代码>默认值
方法可以解决您的问题:)是的,我正在使用Java8。你能帮我什么忙吗DI不知道Java8中的默认方法。这正是我需要的。谢谢!回答得很好!它是委托模式的一个实现。谢谢;)