0
    public class Student{
    @NotNull
    private Course course= null;

    @CustomValidation(enumCourse = course)
    private String details = null;
    }
}

How can i pass the course variable to CustomValidation annotation? Im getting an error saying that course must be an enum constant expression.

I have written a custom validation interface and validator too.

2 Answers 2

2

Annotation property must be constant at compile time.

You cannot use variable there.

The keyword here is cross fields validation.

You have two option:

  1. Create annotation at class level. There you have access to all properties of class and validation should be done easy
  2. Or create annotation at method level which return all necessary fields for validations.

    @CustomAnnotations
    Pair<Course, String> getCourseAndDetailForValidation() {
       return Pair.of(course, details)
    }
    

    You can change return type to match your taste, it may be a List, an Array, wrapper objects...

Sign up to request clarification or add additional context in comments.

2 Comments

How do i pass this method to @CustomValidation(enumCourse = course) ?
Did you read about custom validation? Once you annotated your method with @CustomAnnotation, in your CustomAnnotationValidator.java class, you have access those properties (course and details) inside isValid() method, and you can implement your logic there
0

It's specified by section 9.6.1 of the JLS. The annotation member types must be one of:

primitive String Class an Enum another Annotation an array of any of the above

Course must be one of those types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.