Friday 27 June 2014

@Inherited

It is used to indicate that annotations on a class C corresponding to a given annotation type are inherited by subclasses of C.

Running without Inherited Annotation
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation1{
    String value();
}

@MyAnnotation1("abcd")
public class SuperClass {

}

import java.lang.annotation.Annotation;

public class SubClass extends SuperClass{    
    public static void main(String args[]){
        Class myClass = SubClass.class;
        Annotation ann[] = myClass.getAnnotations();
        for(int i=0; i< ann.length; i++){
            System.out.println(ann[i].toString());
        }
    }
}

Output prints nothing. Now try to add @Inherited Annotation to MyAnnotation1 and re compile and run the SubClass.java.

Running with Inherited Annotation 
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation1{
    String value();
} 


Output

@MyAnnotation1(value=abcd)




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment