簡體   English   中英

如何在Java中的同一個類中為多個枚舉成員使用toString()方法

[英]how to use the toString() method for multiple enum members in same class in Java

我正在嘗試為同一個類中的多個枚舉成員添加更多用戶友好的描述。 現在我只讓每個枚舉以小寫形式返回:

public enum Part {
    ROTOR, DOUBLE_SWITCH, 100_BULB, 75_BULB, 
    SMALL_GAUGE, LARGE_GAUGE, DRIVER;

    private final String description;

    Part() {
      description = toString().toLowerCase();
    }

    Part(String description) {
      this.description = description;
    }

    public String getDescription() {
      return description;
    }
}

有沒有辦法給每個枚舉值一個更加用戶友好的名稱,我可以通過toString()為每個Part成員顯示? 例如,當我對部件進行交互時:

for (Part part : Part.values()) {
System.out.println(part.toString());
}

而不是獲得文字列表:

ROTOR
DOUBLE_SWITCH
100_BULB
75_BULB 
SMALL_GAUGE
LARGE_GAUGE
DRIVER

我希望對每個項目給出有意義的描述,這樣我就可以輸出如下內容:

Standard Rotor
Double Switch
100 W bulb
75 W bulb 
Small Gauge
Large Gauge
Torque Driver

所以我想知道是否有辦法為我的Part枚舉類中的每個枚舉成員提供有意義的描述。

非常感謝

枚舉實際上是偽裝的類,被迫成為單個實例。 您可以執行以下操作,為每個人命名。 你可以在構造函數中給它任意數量的屬性。 它不會影響您的引用方式。 在下面的示例中,ROTOR將具有“This is a rotor”的字符串表示。

public enum Part {
  ROTOR("This is a rotor");

  private final String name;

  Part(final String name) {
      this.name = name;
  } 

  @Override
  public String toString() {
      return name;
  }
}

是的,你已經有了一個描述的構造函數。 為什么不使用它?

public enum Part {
    ROTOR<b>("Rotor")</b>, DOUBLE_SWITCH<b>("Double Switch")</b>, 100_BULB, 75_BULB, 
    SMALL_GAUGE, LARGE_GAUGE, DRIVER;

    private final String description;

    Part() {
      description = toString().toLowerCase();
    }

    Part(String description) {
      this.description = description;
    }

    public String getDescription() {
      return description;
    }
}

暫無
暫無

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

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