Tuesday, November 29, 2016

Change enum values by passing values

Following code can be used to change the enum return value as required by passing parameters.

import java.text.MessageFormat;

public enum Errors {
     USERNAME_NOT_FOUND("User not found"),
     USERNAME_EXISTS("Username {0} already exists."),
     USERNAME_CONTAINS_INVALID_CHARS("Username {0} contains invalid characters {1}.");

     private final String message;

     Errors(String message) {
          this.message = message;
     }

     @Override
     public String toString() {
          return message;
     }

     public String getMessage(Object... args) {
          return MessageFormat.format(message, args);
     }
      
     public static void main(String args[]) {

System.out.println(Errors.USERNAME_NOT_FOUND);          System.out.println(Errors.USERNAME_EXISTS.getMessage("username"));  System.out.println(Errors.USERNAME_CONTAINS_INVALID_CHARS.getMessage("us%ername", "%"));

     }
}


No comments:

Post a Comment