Wednesday, 27 July 2016

Create an annotation in Java

CustomAnnotation.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.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) {
           new TestCustomAnnotation().testAnnotation();
     }
     @CustomAnnotation(
                studentName="Rajesh",
                stuAddress="Mathura, India"
     )
     public void testAnnotation() {
           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...