0

I have an Enum in Java and I change it into enumerated annotations like that:

public static final String PING = "ping";
public static final String PING_BACK = "ping.back";
public static final String REQUEST_MODE_NORMAL = "request_mode_normal";
public static final String ERROR_MESSAGE = "error_message";

@StringDef({PING, PING_BACK, REQUEST_MODE_NORMAL, ERROR_MESSAGE})
@Retention(RetentionPolicy.SOURCE)
public @interface Type {
}

@MessageCall.Type
private String mMessage;

Now I have another String value are inputted by user and I want to pass this into mMesssage field. That's a unknown value at compile time so I have to check this like that:

public MessageCall(String message) {
    switch (message) {
        case PING:
            mMessage = PING;
            break;
        case PING_BACK:
            mMessage = PING_BACK;
            break;
        case REQUEST_MODE_NORMAL:
            mMessage = REQUEST_MODE_NORMAL;
            break;
        default:
            mMessage = ERROR_MESSAGE;
    }
}

I think that's so bad solution for me now and I wounder that "have any solution else to resolve my problem".

Thank you for your support.

Trần Đức Tâm
  • 4,037
  • 3
  • 30
  • 58

1 Answers1

2

As you are mainly just re-assigning the existing value to a new variable you can do it like:

public MessageCall(String message) {

    if (message.equals(PING) || 
        message.equals(PING_BACK) ||
        message.equals(REQUEST_MODE_NORMAL)) 
    {
         mMessage = message;
    }
    else {
         mMessage = ERROR_MESSAGE;
    } 
}

Although maybe a better way could be to create a List that contains your Strings and then check to see if the List contains the message.

List<String> messages = Arrays.asList("ping", "ping_back");
if (messages.contains("ping")) {
     System.out.println("message is ping");
}
if (!messages.contains("test")) {
    System.out.println("no message for test");
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • That's the good solution but not in my case. The enumerated annotations be a best practice from Google for reduce the enum size but I can do something like this `MessageCall.Type.constant(String)`. Let imagine when the type have 40 difference String in this list. I think my source code will become terrible. – Trần Đức Tâm Apr 27 '17 at 02:07