1

I am trying to create validator for parameters, my annotation should always throw exception because methos isValid always return false, here is code:

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 ...");
}

Output of my program is:

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 ...

Additionally i cannot put break-point on Validator class, it is kind of clue. Am i missing something?

Naix
  • 17
  • 6

0 Answers0