0

I am not asking "how to validate enums".

Let's say I have request body like this one:

public class VerifyAccountRequest {
    
    @Email(message = "2")
    private String email;
}

What i am trying to do, instead of hardcoded way, i just want to return message's value from enum class. But IDEA is saying "Attribute value must be constant"

public enum MyEnum {
    EMAIL("2", "info"),
    public String messageCode;
    public String info;
}

public class VerifyAccountRequest {
    
    @Email(message = MyEnum.Email.code) // NOT_WORKING
    private String email;
}

I can also define "2" in the interface, but i don't want to do that:

public interface MyConstant {
    String EMAIL = "2";
}

public class VerifyAccountRequest {
    
    @Email(message = MyConstant.EMAIL) // WORKS, BUT I HAVE TO USE ENUM !!!
    private String email;
}

is it possible to return message value using enum class ?

2
  • Does this answer your question? How to supply Enum value to an annotation from a Constant in Java Commented Oct 30, 2021 at 1:58
  • @HarryCoder, this is actually work around the problem. But at least, i will be able to use one source of truth in my code instead of duplicates. Thanks i am using this solution right now Commented Oct 30, 2021 at 8:27

1 Answer 1

1

The Java rules say that when you have an annotation, and it has a parameter that expects a primitive type (such as an int) or a String, the value must be a constant expression. You are trying to set a value on runtime. However, annotation attributes must have an exact value before the JVM loads the class, it'll show an error otherwise.

The structure element_value can store values of four different types:

  1. a constant from the pool of constants
  2. a class literal
  3. a nested annotation
  4. an array of values

So, a constant from an annotation attribute is a compile-time constant. Otherwise, the compiler wouldn't know what value it should put into the constant pool and use it as an annotation attribute. For more read this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.