如何在Java中的同一个类中为多个枚举成员使用toString()方法

时间:2009-11-14 15:30:09

标签: java enums tostring

我正在尝试为同一个班级中的多个枚举成员添加更多用户友好的描述。现在我只让每个枚举以小写字母返回:

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枚举类中的每个枚举成员提供有意义的描述。

非常感谢

2 个答案:

答案 0 :(得分:9)

枚举实际上是伪装的类,被迫成为单个实例。您可以执行以下操作,为每个人命名。你可以在构造函数中给它任意数量的属性。它不会影响您的引用方式。在下面的例子中,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;
  }
}

答案 1 :(得分:0)

是的,您已经有了一个描述的构造函数。为什么不使用它?

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;
    }
}