Reputation: 38705
So I have something like this
public enum DataType {
RECORD_TYPE("0"),
...
private String code;
private DataType(String code){
this.code = code;
}
public String getCode() {
return code;
}
}
So when I do
System.out.println(DataType.RECORD_TYPE);
It prints out string RECORD_TYPE
, but I want to it to print out 0
, and I dont want to do this
System.out.println(DataType.RECORD_TYPE.getCode());
as I feel that the user will most likely forget to put the getCode()
in. I know Enum does not have toString
method, is there a way for me to change the default behavior when java convert Enum to String?
Upvotes: 0
Views: 415
Reputation: 52448
Add this toString() method to your enum
public String toString() {
return getCode();
}
Upvotes: 2
Reputation: 198023
Sure. Override the toString()
function.
public String toString() {
return code;
}
Upvotes: 3
Reputation: 328578
I know Enum does not have toString method
It actually does have a toString method like any Object
s and you can override it.
Upvotes: 5