如何在 Java 中对同一类中的多个枚举成员使用 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;
}
}
有没有一种方法可以为每个枚举值提供一个更用户友好的名称,我可以通过每个 Part 成员的 toString() 显示该名称?例如,当我对零件进行交互时:
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 枚举类中的成员。
非常感谢
I am trying to add more user friendly descriptions for multiple enum members in the same class. Right now I just have each enum returned in lowercase:
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;
}
}
Is there a way to give each enum value a more user-friendly name which I can display via the toString() for each Part member? For example when I interate over the Parts:
for (Part part : Part.values()) {
System.out.println(part.toString());
}
rather than getting the literal list:
ROTOR
DOUBLE_SWITCH
100_BULB
75_BULB
SMALL_GAUGE
LARGE_GAUGE
DRIVER
I am hoping to give meaningful descriptions to each item so I can output something like:
Standard Rotor
Double Switch
100 W bulb
75 W bulb
Small Gauge
Large Gauge
Torque Driver
So I was wondering if there is a way to give those meaningful descriptions for each enum member in my Part enum class.
Many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
枚举实际上是伪装的类,被迫成为单个实例。您可以执行以下操作来为每个名称指定一个名称。您可以在构造函数中为其指定任意数量的属性。它不会影响您引用它的方式。在下面的示例中,ROTOR 将具有“这是转子”的字符串表示形式。
Enums are really classes in disguise, forced to be a single instance. You can do something like this below to give each a name. You can give it any number of proprties you like in the constructor. It doesn't affect how you reference it. In the example below, ROTOR will have a string representation of "This is a rotor".
是的,您已经有了一个带有描述的构造函数。为什么不使用它呢?
Yes, you already have a constructor that takes a description. Why not use that?