Creating Custom annotations

This article is about to create using own custom annotations on java. This example illustrate how to create  custom annotation to support validation on java object.

1. Create Annotation class

There is a simple method to create annotation class.  Here there are two annotation class named @NotNull and @Length.

@NotNull is for validating the field againsts null value and @Length  is for restricting the length of the string.

filename : NotNull.java


package cc.validations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
public @interface NotNull {

String message();
 }

filename : Length.java

package cc.validations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
public @interface Length {

	int min() default 15;

	String messsage();

	int max() default 50;

}

filename Person.java

package cc.validations.test;

import cc.validations.Length;
import cc.validations.NotNull;

public class Person {

	@NotNull(message = "Firstname cannot be null")
	@Length(min = 15, max = 60, messsage = "Length must be between 15 and 60")
	private String firstName;

	@Length(min = 15, max = 60, messsage = "Length must be between 15 and 60")
	private String middleName;

	@NotNull(message = "Lastname cannot be null")
	@Length(min = 15, max = 60, messsage = "Length must be between 15 and 60")
	private String lastName;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getMiddleName() {
		return middleName;
	}

	public void setMiddleName(String middleName) {
		this.middleName = middleName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

}

2. Putting all together

filename : Main.java

package cc.validations.test;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cc.validations.Length;
import cc.validations.NotNull;

public class Main {

	public static List<String> validate(Object obj) {

		List<String> errors = new ArrayList<String>();
		Field[] fields = obj.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			fields[i].setAccessible(true);
			NotNull annotations = fields[i].getAnnotation(NotNull.class);
			if (annotations != null) {
				try {
					if (fields[i].get(obj) == null) {
						errors.add(annotations.message());
						continue;
					}
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
			}
			// check for length only if @NotNull is present

			if (annotations != null) {
				Length lengthAnnotations = fields[i].getAnnotation(Length.class);
				if (lengthAnnotations != null) {
					try {
						int min = lengthAnnotations.min();
						int max = lengthAnnotations.max();
						String value = (String) fields[i].get(obj);
						if (value.length() < min || value.length() > max) {
							errors.add(fields[i].getName() + ": " + lengthAnnotations.messsage());
						}
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
				}
			}
		}
		return errors;
	}

	public static void main(String args[]) {
		Person p = new Person();
		p.setFirstName("Kusum");
		p.setLastName("Adhikari");
		List<String> msgs = validate(p);
		for (String msg : msgs) {
			System.out.println(msg);
		}
	}
}

Leave a comment

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.