Reputation: 97
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!
Upvotes: 1
Views: 73
Reputation: 213371
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; }
}
Upvotes: 6
Reputation: 37875
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
.
Upvotes: 0
Reputation: 426
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.
Upvotes: 1