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 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).
The name()
method belongs to the Enum class , so all enum values automatically have this method available.
By default Enum#toString will return its name. You should be able to just do your first expression. The String concatenation (+ operator) will call toString automatically.
enum TestEnum {
ATESTSTRING;
public static void main(String[] args) {
System.out.println(ATESTSTRING + " is a test string");
}
}
Will output ATESTSTRING is a test string
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.