我正在尝试为参数创建验证器,我的注释应该总是抛出异常因为methos isValid总是返回false,这里是代码:
CustomAnnotation.java
@Target( {ElementType.PARAMETER, ElementType.FIELD} )
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CustomAnnotationValidator.class)
public @interface CustomAnnotation {
String message() default "some error msg";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
CustomAnnotationValidator.java
public class CustomAnnotationValidator implements ConstraintValidator<CustomAnnotation, String> {
@Override
public void initialize(CustomAnnotation customAnnotation) {
}
@Override
public boolean isValid(String token, ConstraintValidatorContext constraintValidatorContext) {
return false;
}
Main.java
public class Main {
public static void main(String[] args) {
Class annotationOfMethod = Main.class.getMethods()[1].getParameterAnnotations()[0][0].annotationType();
String msg = "My method have paramether with annotation: " + annotationOfMethod.toString();
System.out.println(msg);
Annotation[] annotationsOfAnnotation = annotationOfMethod.getAnnotations();
String msg2 = "CustomAnnotation is annotated by: \n" + annotationsOfAnnotation[0] + "\n" + annotationsOfAnnotation[1] + "\n" + annotationsOfAnnotation[2];
System.out.println(msg2);
checkAnnotation("text");
}
public static void checkAnnotation(@CustomAnnotation String string) {
System.out.println("\nAnnotation is not working ...");
}
我的程序输出是:
My method have paramether with annotation: interface CustomAnnotation
CustomAnnotation is annotated by:
@java.lang.annotation.Target(value=[PARAMETER, FIELD])
@java.lang.annotation.Retention(value=RUNTIME)
@javax.validation.Constraint(validatedBy=[class CustomAnnotationValidator])
Annotation is not working ...
另外我不能在Validator类上放置断点,这是一种线索。 我错过了什么吗?