Java Reference
In-Depth Information
Listing 1-22 contains the code for a RepeatableAnnTest class. The class declaration has been annotated with the
ChangeLog annotation twice. The main() method accesses the repeated annotations on the class declaration using the
above discussed both methods.
Listing 1-22. Accessing Instances of Repeatable Annotations at Runtime
// RepeatableAnnTest.java
package com.jdojo.annotation;
@ChangeLog(date = "02/01/2014", comments = "Declared the class")
@ChangeLog(date = "02/22/2014", comments = "Added the main() method")
public class RepeatableAnnTest {
public static void main(String[] args) {
Class<RepeatableAnnTest> mainClass = RepeatableAnnTest.class;
Class<ChangeLog> annClass = ChangeLog.class;
// Access annotations using the ChangeLog type
System.out.println("Using the ChangeLog type...");
ChangeLog[] annList = mainClass.getAnnotationsByType(ChangeLog.class);
for (ChangeLog log : annList) {
System.out.println("Date=" + log.date() +
", Comments=" + log.comments());
}
// Access annotations using the ChangeLogs containing annotation type
System.out.println("\nUsing the ChangeLogs type...");
Class<ChangeLogs> containingAnnClass = ChangeLogs.class;
ChangeLogs logs = mainClass.getAnnotation(containingAnnClass);
for (ChangeLog log : logs.value()) {
System.out.println("Date=" + log.date() +
", Comments=" + log.comments());
}
}
}
Using the ChangeLog type...
Date=02/01/2014, Comments=Declared the class
Date=02/22/2014, Comments=Added the main() method
Using the ChangeLogs type...
Date=02/01/2014, Comments=Declared the class
Date=02/22/2014, Comments=Added the main() method
Evolving Annotation Types
An annotation type can evolve without breaking the existing code that uses it. If you add a new element to an
annotation type, you need supply its default value. All existing instances of the annotation will use the default value
for the new elements. If you add a new element to an existing annotation type without specifying a default value for
the element, the code that uses the annotation will break.
 
Search WWH ::




Custom Search