简体   繁体   中英

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM