[英]Questions about Enums in Java
How can I say something like: 我怎么说:
System.out.println(Enum.ATESTSTRING + " is a test string!");
and not: 并不是:
System.out.println(Enum.ATESTSTRING.getString() + " is a test string!");
Thanks! 谢谢!
Override toString()
method in your enum
: 覆盖
enum
toString()
方法:
enum MyEnum {
ATESTSTRING("A test String");
private final String value;
MyEnum(String value) { this.value = value; }
@Override
public String toString() {return value; }
}
Enum.ATESTSTRING.toString()
or Enum.ATESTSTRING.name()
(if you want to use your toString()
for something else). Enum.ATESTSTRING.toString()
或Enum.ATESTSTRING.name()
(如果您想将toString()
用于其他用途)。
The name()
method belongs to the Enum class , so all enum values automatically have this method available. name()
方法属于Enum类 ,因此所有枚举值都会自动使该方法可用。
By default Enum#toString will return its name. 默认情况下, Enum#toString将返回其名称。 You should be able to just do your first expression.
您应该可以只做第一个表情。 The String concatenation (+ operator) will call toString automatically.
字符串串联(+运算符)将自动调用toString。
enum TestEnum {
ATESTSTRING;
public static void main(String[] args) {
System.out.println(ATESTSTRING + " is a test string");
}
}
Will output ATESTSTRING is a test string
. 将输出
ATESTSTRING is a test string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.