Example of Custom Annotation in Java
February 23, 2013
In jdk 1.5, a new feature annotation has been introduced. Annotation is applied on java because of hiding complex code. Annotation makes it easy to concentrate on our business logic. Other complex code is left on Annotation that is handled by JVM. Let’s understand step by step to create custom annotation. The package java.lang.annotation provides interfaces that are used to create custom annotation.
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation { int maxLength(); }
package com.concretepage; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation { int maxLength(); } class Person { @MyAnnotation(maxLength = 10) public String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class MyAnnotationHanlder { public void handle(Object ob) throws Exception { Field[] fields = ob.getClass().getFields(); for (Field field : fields) { if (field.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation myAnn = field.getAnnotation(MyAnnotation.class); int maxLen=myAnn.maxLength(); System.out.println("Max length is:"+maxLen); if(maxLen<field.get(ob).toString().length()){ throw new Exception("You have eneterd string greater than max length."+maxLen); } } } } } public class CustomAnnotationTest { public static void main(String[] args) throws Exception { MyAnnotationHanlder parser = new MyAnnotationHanlder(); Person person= new Person(); person.setName("CONCRETEPAGE"); parser.handle(person); } }
Max length is:10 Exception in thread "main" java.lang.Exception: You have eneterd string greater than max length.10 at com.concretepage.MyAnnotationHanlder.handle(AnnotationTest.java:43) at com.concretepage.AnnotationTest.main(AnnotationTest.java:57)