我正在尝试 @Pattern
验证输入的注解
@Pattern(regexp="[A-Za-z0-9_.]*", message="Name can only contain alphanumeric characters and underscores and dots")
public String getName() {
return name;
}
我还希望错误 message
包含传递的 name
的实际值。如何在注释调用中访问它?例如,我想要这样的东西:
@Pattern(regexp="[A-Za-z0-9_.]*", message="Name can only contain alphanumeric characters and underscores and dots. Provided name: " + name + " is not valid")
我尝试了这个并得到了一个错误提示 The value for annotation attribute Pattern.message must be a constant expression
。有什么方法可以在注释定义中获取实际变量值(特别是错误消息)?我想通过显示实际提供的值来使错误消息更有用。
最佳答案
您可能需要自定义约束来覆盖@Pattern 生成的默认错误消息。查看相关文档 here .
关于java - 如何在 java 中获取带注释的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15063838/