簡體   English   中英

用於switch語句的Java擴展枚舉

[英]Java extended enum for switch statement

我有以下代碼

public interface EnumInterface{
   public String getTitle();
}


public enum Enum1 extends EnumInterface{
  private String title;
  Enum1(String title){
    this.title = title;
  }

  A("Apple"),B("Ball");
  @Override
  public String getTitle(){
    return title;
  }
}

public enum Enum2 extends EnumInterface{
  private String title;
  Enum1(String title){
    this.title = title;
  }

  C("Cat"),D("Doll");
  @Override
  public String getTitle(){
    return title;
  }
}

我在其他課程中使用它如下

private EnumInterface[] enumList;//declared globally.

if(flagTrue){
  enumList = Enum1.values();
}else{
  enumList = Enum2.values();
}
....
....
private method1(int position){
  switch(enumList[postion]){
    case A:....
           break;
    case B:....
           break;
    case C:....
           break;
    case D:....
           break;
  }
}

我收到以下編譯時錯誤

無法打開EnumInterface類型的值。 只允許使用可轉換的int值或枚舉變量。

我做了我的研究,發現如果我這樣做,'開關'的情況是不可能的。

在這種情況下,Switch語句絕對不是您想要的。 即使上面的例子有效,並且沒有理由,你的結果也會完全錯誤。 上枚舉交換機使用枚舉序,這是0 Enum1.A ,1 Enum1.B ,0為Enum2.C為,和1 Enum2.D使用上述你的類。 你可以看出為什么這會是一個非常糟糕的主意。

您的EnumInterface類不以任何方式綁定Java類型enum ,它只定義實現它的任何類並提供getTitle()方法。 這可能是Enum1Enum2或任何其他甚至可能不是Enum的類。 因此,當您想要基於EnumInterface進行切換時,您需要問問自己實際想要打開的內容。 它是你想要用作條件的標題,還是你定義的枚舉帶來了其他東西?

現在,我將給你懷疑的好處,並假設無論你想做什么,它都需要從一個Enum鍵入。 我還假設您無論出於何種原因都無法組合Enum1Enum2 以下是我完全過度設計的解決方案:

public interface EnumInterface {

    public String getTitle();

    public void processEvent(SwitchLogicClass e);
}


public enum Enum1 implements EnumInterface{

    A("Apple"){
        public void processEvent(SwitchLogicClass e){
            //Any A specific Logic
            e.doSomethingA();
        }
    },
    B("Ball"){
        public void processEvent(SwitchLogicClass e){
            //Any B specific Logic
            e.doSomethingB();
        }
    };

    private String title;
    Enum1(String title){
        this.title = title;
    }


    @Override
    public String getTitle(){
        return title;
    }
}

重復Enum2。 假設下一個類叫做SwitchLogicClass

private EnumInterface[] enumList;//declared globally.

if(flagTrue){
    enumList = Enum1.values();
}else{
    enumList = Enum2.values();
}
....
....
private method1(int position){
    EnumInterface[position].processEvent(this);
}


public void doSomethingA(){
    //Whatever you needed to switch on A for
}

public void doSomethingB(){
    //Whatever you needed to switch on B for
}

....
....

你幾乎肯定需要根據你需要使用的抽象模式進行重構,但上面是我能用你所知道的代碼做的最好的。

擴展完成了什么,使用簡單的java enum無法完成? 你可以使用if else塊並調用equals方法。

暫無
暫無

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

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