Wednesday, 27 July 2016

Create an annotation in Java

CustomAnnotation.java
importjava.lang.annotation.ElementType;
importjava.lang.annotation.Retention;
importjava.lang.annotation.RetentionPolicy;
importjava.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
     int studentAge() default 21;
     String studentName();
     String stuAddress();
     String stuStream() default "CS";
}

How to use the field of Annotation in Java?

TestCustomAnnotation.java
package annotations;
import java.lang.reflect.Method;
public class TestCustomAnnotation {
     public static void main(String[] args) {
           newTestCustomAnnotation().testAnnotation();
     }
     @CustomAnnotation(
                studentName="Rajesh",
                stuAddress="Mathura, India"
     )
     public voidtestAnnotation() {
           try {
                Class<? extends TestCustomAnnotation> cls = this.getClass();
                Method method = cls.getMethod("testAnnotation");
               
                CustomAnnotation myAnno = method.getAnnotation(CustomAnnotation.class);
               
                System.out.println("Name: "+myAnno.studentName());
                System.out.println("Address: "+myAnno.stuAddress());
                System.out.println("Age: "+myAnno.studentAge());
                System.out.println("Stream: "+myAnno.stuStream());
               
           } catch(NoSuchMethodException e) {
           }
     }
}
Output:
Name: Rajesh
Address: Mathura, India
Age: 21
Stream: CS

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...