Wednesday, 27 July 2016

Create an annotation in Java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public @interface CustomAnnotation {
     int studentAge() default 21;
     String studentName();
     String stuAddress();
     String stuStream() default "CS";

How to use the field of Annotation in Java?
package annotations;
import java.lang.reflect.Method;
public class TestCustomAnnotation {
     public static void main(String[] args) {
           new TestCustomAnnotation().testAnnotation();
                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) {
Name: Rajesh
Address: Mathura, India
Age: 21
Stream: CS

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...