英文:
How to provide enum string as value of an attribute?
问题
Enum: -
public enum StatusEnum {
MISSING("00"), INVALID("01");
// ...
}
我试图将这些字符串 "MISSING"、"INVALID" 用作 JSR 验证的属性字段:-
public class SomePojo {
@NotNull(message = "MISSING") // 这当然是无效的,但这是我想要的
@Pattern(regexp = "some pattern", message = "INVALID")
private String someField;
}
我需要这样做是因为当我以编程方式验证一个对象与此类(javax 验证)匹配时,我希望 constraintViolation 对象的 getMessage 方法给我枚举字符串,以便我可以轻松地解释错误。
我知道我可以直接放置字符串,但更改枚举也需要更改属性,这是很麻烦的。
英文:
Enum:-
public StatusEnum {
MISSING("00"), INVALID("01");
....
}
I'm trying to use these strings "MISSING", "INVALID" as an attribute field for JSR Validations:-
public class SomePojo{
@NotNull(message = StatusEnum.MISSING.toString()) //this is invalid ofc, but this is what i want
@Pattern(regexp="some pattern", message = StatusEnum.INVALID.toString())
private string someField;
}
I need this so that when i programmatically validate an object against this class (javax validations), i want the constraintViolation object's getMessage to give me the enum string so that I can easily interpret the error.
I know i can put the strings directly but changing the enum will need change in the attributes as well which is a pain.
答案1
得分: 0
以下是翻译好的内容:
消息的值必须是一个常量表达式。您可以使用一个包含常量的类来替代枚举:
public class Status{
public static final String MISSING = "00";
public static final String INVALID = "01";
}
然后在代码中使用它:
public class SomePojo{
@NotNull(message = Status.MISSING)
@Pattern(regexp="some pattern", message = Status.INVALID)
private String someField;
}
英文:
The value for the message must be a constant expression. Instead of an Enum you can use a class with constants:
public class Status{
public static final String MISSING = "00";
public static final String INVALID = "01";
}
And then use it:
public class SomePojo{
@NotNull(message = Status.MISSING)
@Pattern(regexp="some pattern", message = Status.INVALID)
private string someField;
}
专注分享java语言的经验与见解,让所有开发者获益!
评论