Writing own annotation.

We can write our own annotations. Below is an example.
Here the annotation is used in both method and class.

package demo;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
    String name();
    int age();
}

@MyAnnotation(name="bhabani",age=28)
public class MyAnnotationTest {

    public static void main(String[] args) throws Exception {
        Class classs = MyAnnotationTest.class;
        MyAnnotation annotation = classs.getAnnotation(MyAnnotation.class);
        System.out.println("Name is "+annotation.name()+" Age is "+annotation.age());
        MyAnnotationTest test = new MyAnnotationTest();
        test.fun();
    }
   
    @MyAnnotation(name = "fun", age=1)
    public void fun() throws Exception{
        Class testClass = MyAnnotationTest.class;
        Method funMethod = testClass.getMethod("fun");
        MyAnnotation annotation = funMethod.getAnnotation(MyAnnotation.class);
        System.out.println("Name is "+annotation.name()+" Age is "+annotation.age());
    }
}



No comments:

Post a Comment