我有以下注释类
public @interface Size {
int min() default 1;
int max() default 100;
String message() default "Age between min - max";
}
在默认情况下,我想要andmessage()
的默认值。在这里简单地写是行不通的。有什么直接的方法吗?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
是另一个只保存错误的类。