에 필드 값을 사용하여 나는 기본 message()
에서 다음 주석 클래스를자바 주석 : 다른 필드
public @interface Size {
int min() default 1;
int max() default 100;
String message() default "Age between min - max";
}
다음 한 나는 min()
과 max()
의 기본 값을합니다. 단순히 String message() default "Age between" + min() + "-" + max();
을 쓰는 것은 여기서 작동하지 않습니다. 직접 할 수있는 방법이 있습니까?
편집 1 : 나는 여기에 min()
및 max()
값을 설정할 수 있습니다, 너무
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;
}
}
이제 사람 클래스가 있습니다. 따라서 사용자가 잘못된 입력을하면 message()
은 그에 따라 프린터가됩니다.
EDIT 2 : As @nicolas wanted. 여기에 입력을 확인하고 오류 메시지를 인쇄하는 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
은 오류를 저장하는 또 다른 클래스입니다.
주석 값이 상수를해야합니다, 당신은 분/최대 – AdamSkywalker
오히려 상수 만이 기본값으로 예상되기 때문에 메시지를 인쇄 할 코드에서 관리해야 호출 할 수 없습니다 이미 –
표시를 설명 예상 결과를 얻기 위해 입력을 향상시키고 자한다면 메시지를 표시하는 코드 –