Kevindra
Kevindra

Reputation: 1762

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.

Upvotes: 1

Views: 3668

Answers (1)

Solomon Slow
Solomon Slow

Reputation: 27115

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.

Upvotes: 1

Related Questions