Java Reference
In-Depth Information
// Read annotation of method declaration
System.out.println("Method annotations:");
Method[] m = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
System.out.println("Annotations for method:" + m[i].getName());
printAnnotations(m[i]);
}
}
public static void printAnnotations(AnnotatedElement programElement) {
Annotation[] annList = programElement.getAnnotations();
for (int i = 0; i < annList.length; i++) {
System.out.println(annList[i]);
if (annList[i] instanceof Version) {
Version v = (Version)annList[i];
int major = v.major();
int minor = v.minor();
System.out.println("Found Version annotation: " +
"major =" + major + ", minor=" + minor);
}
}
System.out.println();
}
}
Annotations for class:com.jdojo.annotation.AccessAnnotation
@com.jdojo.annotation.Version(major=1, minor=0)
Found Version annotation: major =1, minor=0
Annotations for package:com.jdojo.annotation
@com.jdojo.annotation.Version(major=1, minor=0)
Found Version annotation: major =1, minor=0
Method annotations:
Annotations for method:testMethod1
@com.jdojo.annotation.Version(major=1, minor=1)
Found Version annotation: major =1, minor=1
Annotations for method:testMethod2
@com.jdojo.annotation.Version(major=1, minor=2)
Found Version annotation: major =1, minor=2
@java.lang.Deprecated()
Accessing instances of a repeatable annotation is a little different. Recall that a repeatable annotation has
a companion containing an annotation type. For example, you declared a ChangeLogs annotation type that is a
containing annotation type for the ChangeLog repeatable annotation type. You can access repeated annotations using
either the annotation type or the containing annotation type. Use the getAnnotationsByType() method passing it the
class reference of the repeatable annotation type to get the instances of the repeatable annotation in an array. Use the
getAnnotation() method passing it the class reference of the containing annotation type to get the instances of the
repeatable annotation as an instance of its containing annotation type.
 
Search WWH ::




Custom Search