[英]Java annotation: using a field value into another field
我有以下注释类
public @interface Size {
int min() default 1;
int max() default 100;
String message() default "Age between min - max";
}
在这里,在默认message()
我想要min()
和max()
的默认值。 简单地编写String message() default "Age between" + min() + "-" + max();
在这里不工作。 有直接的方法吗?
编辑1:我也有一个人班
public class Person {
@Size(max = 10)
private String name;
@Size(min = 18, message = "Age can not be less than {min}")
private int age;
public Person(String s, int i) {
this.name = s;
this.age = i;
}
}
现在,可以在此处设置min()
和max()
值。 因此,如果用户输入错误,则message()
将被相应地打印。
编辑2:如@nicolas想要的。 这里的AnnonatedValidator
类用于验证输入和打印错误消息。
public class AnnotatedValidator {
public static void validate(Person p, List<ValidationError> errors) {
try {
Field[] fields = p.getClass().getDeclaredFields();
for(Field field : fields) {
if(field.getType().equals(String.class)){
field.setAccessible(true);
String string = (String)field.get(p);
Annotation[] annotationsName = field.getDeclaredAnnotations();
for (Annotation annotation : annotationsName){
if (annotation instanceof Size){
Size size = (Size) annotation;
if (string.length() < size.min() || string.length() > size.max()) {
error(size, errors);
}
}
}
} else if (field.getType().equals(int.class)) {
field.setAccessible(true);
int integer = (Integer)field.get(p);
Annotation[] annotationsAge = field.getDeclaredAnnotations();
for (Annotation annotation : annotationsAge){
if (annotation instanceof Size){
Size size = (Size) annotation;
if (integer < size.min() || integer > size.max()) {
error(size,errors);
}
}
}
}
}
}catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public static void print(List<ValidationError> errors) {
for (int i = 0; i < errors.size(); i++){
System.out.println("Errors: " + errors.get(i).getError());
}
}
public static void error (Size size, List<ValidationError> errors) {
String error = size.message();
if (!error.equals(null)) {
if (error.contains("min")) {
error = error.replace("min", ""+size.min());
}
if (error.contains("max")){
error = error.replace("max", ""+size.max());
}
}
ValidationError v = new ValidationError();
v.setError(error);
errors.add(v);
}
}
ValidationError
是另一个仅保存错误的类。
否,如Java语言规范所规定 , String
类型的default
值必须为常量表达式。
如果元素类型与元素值不匹配,则是编译时错误。 当且仅当以下条件之一为真时,元素类型
T
与元素值V
相称:
- [...]
T
不是数组类型,并且V
的类型与T
兼容(第5.2节),并且:
- [...]
- 如果
T
是原始类型或String
,则V
是常数表达式(第15.28节)。
另一个注释元素的调用不是常量表达式。
您需要在管理注释使用的组件中进行处理。 将default
消息声明为某些特殊值。
String message() default "REPLACE_ME";
然后在构造消息时检查它。 例如
Field field = ... // get 'age' field
Size size = field.getAnnotation(Size.class);
if (size != null) {
String message = size.message();
if (message.equals("REPLACE_ME")) {
message = "Age between " + size.min() + " - " + size.max() + ".";
}
}
int min = size.min();
int max = size.max();
// if field is of type int
int value = field.getInt(instance);
if (value > max || value < min) {
throw new ConstraintViolationException(message);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.