0

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?

3 Answers 3

5

I know Enum does not have toString method

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

Sign up to request clarification or add additional context in comments.

Comments

3

Sure. Override the toString() function.

public String toString() {
  return code;
}

Comments

2

Add this toString() method to your enum

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.