I have a requirement to create a custom Annotation which when applied over a method checks and validates the input parameters (Primitive and non-primitive) against various checks. And if checks fail should return a error message directly.
While searching I have come across use of AbstractProcessor and ConstraintValidator when we create a custom annotation. Being new to creating custom annotation, I would like to understand how to go ahead implementing my problem statement.
First of all, you need to understand that you're talking about two different things.
TL;DR: compile-time vs run-time - you need run-time
An Annotation processor is an abstract term to identify a process which runs during compile time, and which is able to scan the source files, the ones which have a .java
extension.
The Annotation processor implementation might throw warnings, or even errors to stop the compilation task, based on arbitrary checks.
Example: "I noticed someone passed a null
value to my method, it's a error! Stop everything!"
The starting point for implementing an Annotation processor is the AbstractProcessor
base class, or the Processor
interface (documentation).
You'd also need, unlike the ConstraintValidator
implementation, to register it explicitly via a processor metadata file, which must be located under a standard directory inside the produced JAR
artifact.
META-INF/services/javax.annotation.processing.Processor
What is needed to create an Annotation processor is already included in the standard JDK. You don't need external dependencies.
On the other hand, a ConstraintValidator
identifies an interface which is shipped with the Validation API module, under the package javax.validation
. There are different implementations of this API, but the most used one is Hibernate Validator
(documentation).
The validation which this interface provides are verified at runtime.
Unlike the Annotation processor, the Validation API implementation must be provided manually, e.g.
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.15.Final</version>
</dependency>
You wrote
when applied over a method checks and validates the input parameters (Primitive and non-primitive) against various checks
It seems you need to write run-time checks, which means the Validation API is the road to take.