How to Create Custom Field Validator Annotation In Java
Creating custom annotation in Java for field validation
1. Introduction
Java annotation are a form of metadata that can be added to the code which provides information to the compiler or runtime environment.
This information can be used for various use cases such as providing hint to the compiler, adding code generation or providing information to frameworks etc.
In this article learn about annotation and will create annotation for field validation in class.
🚀 Java + Spring Boot + SQL Interview + Certification Prep 🚀
🎯 Perfect for aspiring developers, job switchers & interview prep warriors!🔥 What’s Inside (PDF format):
Grokking the Java Interview (Vol 1 & 2)
Grokking the Spring Boot Interview
Grokking the SQL Interview
Java SE 17 Developer Certification (1Z0-829) Guide
250+ Spring Framework Certification Practice Questions
✅ Bonus: Free Sample Copies of Java, Spring Boot & Spring Questions
2. Annotation Explained!
Java Annotations are kind of markers that can be added to classes, methods, fields, etc.
By adding annotations to the Java classes, methods, or fields it provides metadata information to the compiler or runtime environment.
Annotation start with “@” symbol and can be built in or custom.
For example, `@Component`, `@Repository` are examples of built-in annotation in Spring framework.
Annotation Interface
First we need to define our annotation `CustomAnnotation` as interface.
We need to mark this annotation with @Retention and @Target .
@Retention (RetentionPolicy.RUNTIME) specifies that annotation will be retained at runtine.
@Target ({ ElementType.TYPE, ElementType.METHOD }) restricts annotation to be applicable on `Class` and `Method`.
Marking Annotation
Now lets mark target class and method with the annotation. We need to pass the metadata info which value and count that we defined in annotation.
Reading metadata
Now that we have annotation defined and used, lets read them at runtime.
We can get class level metadata using `Class.getAnnotation()` and method level metadata with `Method.getAnnotation()`.
Once we have annotation instance we can access its property value by simple method call.
In order to access value of class , we can just call `annotation.value()`.
Output
As we can see below we got class & method metadata value .
value: a_class, count: 2
value: a_method
count: 1
Now lets create our own annotation to validate fields in Java class.
3. Creating Custom Field Validator Annotation
Now lets extend our basic example and create something useful.
Lets create two annotation that will help us validating field in java class.
We will create @NotNull and @Length annotation.
@NotNull: it will check if the annotated field is non null . if its null then throws exception
@Length: it will check if the annoted field respects min or max length passed to this annotation.
Lets create `Customer` POJO / record and annotate filed with appropriate annotation.
For password we are making sure its not null and min size 28 and max 100.
For username and emailId we are checking if its not null.
Now lets write validation logic that will read above annotation and metadata at runtime, then perform validation and throw exception with the provided message if required.
At first lets get all the fields from customer record.
Now lets iterate over each field and get all the annotation for that field.
For each annotation we get value and handle it based on annotation type.
Here is the logic to get object value.
Here is the logic to get all the annoation type for the field.
Handle logic takes the typeName of the annotation and operate on it.
For NotNull we check if the fieldVal null , if it is then we extract the message and throw `IllegalArgumentException`.
For Length, we are extracting min and max length , then we are checking if the fieldVal length lies in that range or not.
If not then we throw `IllegalArgumentException` with custom error message.
Output
it throws password length not matching error.
4. Conclusion
Annotation are used extensively in Java developement and certainly its all over used inside Framework like Spring.
In this article we learnt about Annotation in Java. We also build our own field validator annotation.
Some Useful Resources:
Upgrade your Java skills with Grokking the Java Interview.
Crack Spring Boot Interview with Grokking the Spring Boot Interview [ Free Copy ]