2013-05-03 1 views
0

다른 속성보다 먼저 발생하는지 확인하는 클래스 수준 JSR-303 유효성 검사 정의를 생성하려고합니다. 이 유효성 검사는 Calendar 속성에만 의미가 있기 때문에 initialize 메서드에서 속성 유형을 테스트 할 수 있는지 궁금합니다.JSR-303 사용자 정의 유효성 검사기 초기화 메소드의 유형 체크인

내 주석의 정의는 다음과 같습니다

@Target({TYPE, ANNOTATION_TYPE}) 
@Retention(RUNTIME) 
@Constraint(validatedBy = TemporalSequenceValidator.class) 
@Documented 
public @interface TemporalSequence { 

    String message() default "{uk.co.zodiac2000.vcms.constraints.TemporalSequence}"; 
    Class<?>[] groups() default {};  
    Class<? extends Payload>[] payload() default {}; 
    String first(); 
    String second(); 
} 

및 유효성 검사기 구현 :

public class TemporalSequenceValidator implements 
    ConstraintValidator<TemporalSequence, Object> { 
    private String firstFieldName; 
    private String secondFieldName; 

    @Override 
    public void initialize(final TemporalSequence constraintAnnotation) { 
     firstFieldName = constraintAnnotation.first(); 
     secondFieldName = constraintAnnotation.second(); 
     // Is it possible to test type of firstFieldName and 
     // secondFieldName properties here? 
    } 

    @Override 
    public boolean isValid(final Object value, final ConstraintValidatorContext context) { 
     // omitted 
    } 
} 

이 할 수있는 합리적인 것입니까? 내가 사용한다면 어떤 접근 방식을 제안 하시겠습니까? 속성이 올바른 유형이 아닌 경우 어떤 작업을 수행해야합니까?

답변

0

initialize()에있는 확인 된 개체에 액세스 할 수 없으므로 실제로 확인을 수행 할 수 없습니다. 대신 리플렉션을 사용하여 isValid()의 유효성이 검사 된 객체 필드 유형을 확인할 수 있습니다.

if (!Calendar.class.isAssignableFrom( 
    value.getClass().getField(firstFieldName).getType())) { 
    throw new ValidationException("Field " + firstFieldName + " is not of type Calendar."); 
} 
+0

감사합니다. Gunnar. 당신의 대답은 나를 올바른 방향으로 인도하는 데 도움이되었습니다. –