Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

278 Part I: The Java Language


System.out.println(a);

} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}

public static void main(String args[]) {
myMeth();
}
}

The output is shown here:

All annotations for Meta2:
@What(description=An annotation test class)
@MyAnno(str=Meta2, val=99)

All annotations for myMeth:
@What(description=An annotation test method)
@MyAnno(str=Testing, val=100)

The program usesgetAnnotations( )to obtain an array of all annotations associated
with theMeta2class and with themyMeth( )method. As explained,getAnnotations( )
returns an array ofAnnotationobjects. Recall thatAnnotationis a super-interface of all
annotation interfaces and that it overridestoString( )inObject. Thus, when a reference to
anAnnotationis output, itstoString( )method is called to generate a string that describes
the annotation, as the preceding output shows.

The AnnotatedElement Interface


The methodsgetAnnotation( )andgetAnnotations( )used by the preceding examples are
defined by theAnnotatedElementinterface, which is defined injava.lang.reflect. This
interface supports reflection for annotations and is implemented by the classesMethod,Field,
Constructor,Class, andPackage.
In addition togetAnnotation( )andgetAnnotations( ),AnnotatedElementdefines two
other methods. The first isgetDeclaredAnnotations( ), which has this general form:

Annotation[ ] getDeclaredAnnotations( )

It returns all non-inherited annotations present in the invoking object. The second is
isAnnotationPresent( ), which has this general form:

boolean isAnnotationPresent(ClassannoType)

It returns true if the annotation specified byannoTypeis associated with the invoking
object. It returns false otherwise.

NOTEOTE The methodsgetAnnotation( )andisAnnotationPresent( )make use of the generics
feature to ensure type safety. Because generics are not discussed until Chapter 14, their
signatures are shown in this chapter in their raw forms.
Free download pdf