javaenumsannotations

How to use an enum field in annotations in java


I have my own ErrorMessages enum, simply:

public enum ErrorMessages {
  NO_USER(1004, "User not found"),
  UNKNOWN_MODULE(1006, "Module unknown"),
  INCORRECT_DATE(1009, "Incorrect date");

  public final int code;
  private final String messageEng;

  ErrorMessages(int code, String messageEng) {
    this.code = code;
    this.messageEng = messageEng;
  }

  public int getCode() {
    return code;
  }

  public String getMessageEng() {
    return messageEng;
  }
}

And I want to pass the error code to my json-rpc api method as follows:

@JsonRpcMethod("MyMethod")
  @JsonRpcErrors(@JsonRpcError(exception = UserNotFoundException.class, code = ErrorMessages.NO_USER.getCode()))
  boolean myMethod(
      @JsonRpcParam("userId") Integer userId, @JsonRpcParam("apiKey") String apiKey)
      throws UserNotFoundException;

But I get error Attribute value must be constant. I know that values should be passed to annotations at compile time, but I thought it is already known in my case. Is there any way to pass the error code there by getting it from ErrorMessages enum? It would be quite stupid to hardcode the code numbers, having had them already declared.

I've tried to apply some suggestions from threads in sof i found but failed. There was one way to rewrite enum to an interface, but i'd like to avoid it.


Solution

  • You can move the int codes to a separate class:

    public static class ErrorMessagesValues {
        public static final int NO_USER_CODE = 1004;
        public static final int UNKNOWN_MODULE_CODE = 1006;
        public static final int INCORRECT_DATE_CODE = 1009;
    }
    

    then refer to those constants in both the enum:

    public enum ErrorMessages {
        NO_USER(ErrorMessagesValues.NO_USER_CODE, "User not found"),
        UNKNOWN_MODULE(ErrorMessagesValues.UNKNOWN_MODULE_CODE, "Module unknown"),
        INCORRECT_DATE(ErrorMessagesValues.INCORRECT_DATE_CODE, "Incorrect date");
    
        ...
    }
    

    and the annotation:

    @JsonRpcMethod("MyMethod")
    @JsonRpcErrors(@JsonRpcError(exception = UserNotFoundException.class, code = ErrorMessagesValues.NO_USER_CODE))