我想覆盖toString()
我的枚举,Color
. 但是,我不知道如何获取枚举Color
内部实例的值。Color
有没有办法在 Java 中做到这一点?
例子:
public enum Color {
RED,
GREEN,
BLUE,
...
public String toString() {
// return "R" for RED, "G", for GREEN, etc.
}
}
您还可以打开 的类型this
,例如:
public enum Foo {
A, B, C, D
;
@Override
public String toString() {
switch (this) {
case A: return "AYE";
case B: return "BEE";
case C: return "SEE";
case D: return "DEE";
default: throw new IllegalStateException();
}
}
}
public enum Color {
RED("R"),
GREEN("G"),
BLUE("B");
private final String str;
private Color(String s){
str = s;
}
@Override
public String toString() {
return str;
}
}
您可以为枚举使用构造函数。我还没有测试过语法,但这就是想法。
Enum.name()
- 谁会想到它?
但是,在大多数情况下,将任何额外信息保存在构造函数中设置的实例变量中会更有意义。
使用super
和String.substring()
:
public enum Color
{
RED,
GREEN,
BLUE;
public String toString()
{
return "The color is " + super.toString().substring(0, 1);
}
}
默认情况下,Java 会为您执行此操作,它在 .toString() 中返回 .name(),如果您想要与名称不同的内容,您只需要覆盖 toString()。有趣的方法是 .name() 和 .ordinal() 和 .valueOf()。
做你想做的事
.toString(this.name().substring(1));
您可能想要做的是添加一个名为 abbreviation 的属性并将其添加到构造函数中,添加一个 getAbbreviation() 并使用它而不是 .toString()
我发现了这样的东西(未经测试):
public enum Color {
RED{
public String toString() {
return "this is red";
}
},
GREEN{
public String toString() {
return "this is green";
}
},
...
}
希望它有点帮助!