簡體   English   中英

實現相同接口的兩個枚舉共享方法

[英]Two Enums implementing the same interface sharing a method

我有兩個枚舉實現相同的接口

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 Enum作為Enum中的通用類型,但它不能適應我的需要。

Java 8的默認方法應該可以幫到你:)
此功能允許您在界面內實現方法。

public interface MetaEnum {
  String getValue();  

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

遺憾的是,您無法為getter實現default方法,因此您仍然需要一些重復的代碼。

將公共代碼提取到單獨的類:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM