Example of Custom Annotation in Java

By Arvind Rai, November 14, 2023
In Java 5, we can create custom annotations. Java annotation is used to hide 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 us understand step-by-step to create custom annotations. The package java.lang.annotation provides interfaces that are used to create custom annotation.
Find the sample code to create custom annotation.
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    int maxLength();
} 
To create custom annotations, we need to create interface that will be prefixed with @ .
The built-in annotation like @Target is used to define that whether annotation will be applied on field or method.
@Retention defines the retention policy.

Example

Find the complete example to create 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
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us