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", "%"));

     }
}


Wednesday, November 2, 2016

Run different main classes from one project in JAVA

You can use following command to run different classes from one project jar file. Suppose Runner1 and Runner2 are main classes. You want to run both in separately, then you can use the following commands.

java -cp App.jar foo.Runner1
java -cp App.jar foo.Runner2