Search code examples
javaspring-bootspring-validator

How to return validation message using Enum class in spring boot?


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 ?


Solution

  • 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.