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 ?

monstereo
  • 830
  • 11
  • 31
  • Does this answer your question? [How to supply Enum value to an annotation from a Constant in Java](https://stackoverflow.com/questions/13253624/how-to-supply-enum-value-to-an-annotation-from-a-constant-in-java) – Harry Coder Oct 30 '21 at 01: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 – monstereo Oct 30 '21 at 08:27

1 Answers1

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.