简体   繁体   中英

Java enum: Return value other than String

I can't find an answer to this question anywhere so I'm hoping someone can help me out. I'm expecting that what I am asking is not possible, but I wanted to confirm. First, an enum example...

public enum StatusCode {

    SUCCESS(0), GENERAL_ERROR(999), CONNECTION_TIMEOUT_ERROR(1337);

    private int statusCode;

    private StatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public int getStatusCode() {
        return statusCode;
    }
}

As you can see, I am using this enum to force specific status codes. My question is this: Is there a way that I can reference StatusCode.SUCCESS and have it return the int value associated with it? Rather than get into too much detail about what I would like to do, take this example:

public String getStatusMessage(int statusCode) {
    // Map<Integer, String> that contains status messages
    // return String for key statusCode
}

In this example, the syntax for calling this method is getStatusMessage(StatusCode.SUCCESS.getStatusCode()) .

Is there a way to shorten this to getStatusMessage(StatusCode.SUCCESS) ?

I think the second way looks much cleaner and would make my code much more readable. Any ideas? Any help is much appreciated. Thanks in advance!

You mean like this?

public String getStatusMessage(StatusCode code) {
    int status = code.getStatusCode();
    String message = ...do stuff to get message :)
    return message;
}

Luckily for you, EnumMap exists just for that situation.

    private static final Map<StatusCode, String> mapMessage = 
                         new EnumMap<>(StatusCode.class);
    mapMessage.put(SUCCESS, "Success.");
    ...

You don't even need the method getStatusMessage , just call map.getMessage(SUCCESS) .

However maybe you would be better off adding a String message field within StatusMessage and calling the constructors like SUCCESS(0, "Success") and then adding a getter for the message.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM