简体   繁体   中英

Enum with dynamic method parameters

I have an enum defined with some messages, but these messages have %s placeholders. For example:

public enum MyEnum {
    SUCCESS ("Processed successfully", Arrays.asList()),
    ERROR ("Error occurred, reason : %s", Arrays.asList("static reason"));

    private String msg;
    private Object[] params;

    private MyEnum(String msg, Object... params) {
        this.msg = msg;
        this.params = params;
    }

    public String getMessage() {
        return String.format(this.msg, this.params); 
    }
}

So, here I am able to pass static reason for the ERROR enum value. I want clients to pass the error reason and get the generate enum value from getMessage() method.

I thought of achieving this by passing params in the getMessage method instead -

public String getMessage(String... params) {
    return String.format(this.msg, params);
}

Is there any better option than doing this? I want my enum to return dynamically generated messages based on params .

You can't really do anything "dynamic" with the constructor: SUCCESS and ENUM are static references that will each be initialized to point to a new MyEnum instance when the class is loaded. The constructor will be called once each, and then never again during the lifetime of the program.

I thought of achieving this by passing params in the getMessage method instead... Is there any better option than doing this?

No better way that I can think of.

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