Home  >  Core Java

Example of Custom Annotation in Java

By Arvind Rai, 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();
}
To create custom annotation, we need to create interface that will be prefixed with @. The inbuilt annotation like @Target is used to define that whether annotation will be applied on field or method. @Retention defines the retention policy. Find the complete example for how to use custom annotation. We are creating an annotation for max length check.
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);
    }
}
In the above example, if max length is exceeding, then we will get the below error.
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)
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us