Thang Pham
Thang Pham

Reputation: 38705

Java: Make Enum tie to a different String value

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

Answers (3)

Steve McLeod
Steve McLeod

Reputation: 52448

Add this toString() method to your enum

public String toString() {
    return getCode();
}

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198023

Sure. Override the toString() function.

public String toString() {
  return code;
}

Upvotes: 3

assylias
assylias

Reputation: 328578

I know Enum does not have toString method

It actually does have a toString method like any Objects and you can override it.

Upvotes: 5

Related Questions