Wednesday, 27 April 2011

Inherited annotation

  1. Use Inherited to annotate an annotation type, any instance of the annotation type will be inherited.
  2. Use Inherited to annotate a class, the annotation will be inherited by any subclass of the annotated class. If the user queries the annotation type on a class declaration, and the class declaration has no annotation of this type, then the class's parent class will automatically be queried for the annotation type. This process will be repeated until an annotation of this type is found or the root class is reached.

Using this annotation

Suppose that you use your custom annotation called InProgress to mark a class as being in progress. If the Documented meta-annotation is applied correctly, then this will show up in the Javadoc. All is well till here.

Suppose you write a new class and extend the in-progress class. Now remember one this: the superclass is in progress. What about the subclass? For subclass, there will be no indication even in its documentation, that it is incomplete. One would expect to see the InProgress annotation carried through to subclasses. But its not done here. So this is where @Inherited comes into picture.

package com.vaani.annotations.inherited; 
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

// Using the Inherited meta-annotation
/**
* Marker annotation to indicate that a method or class
* is still in progress.
*/
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface InProgress { }

No comments:

Post a Comment