Retention


The java.lang.annotations package includes a meta-annotation type named @Retention. You use meta-annotations to annotate other annotation type declarations. Specifically, you use the @Retention annotation to tell the Java compiler how long to retain annotation information. There are three choices, summarized in Table 15.1.

Table 15.1. Annotation Retention Policies

RetentionPolicy enum

Annotation Disposition

RetentionPolicy.SOURCE

Discarded at compile time

RetentionPolicy.CLASS (default)

Stored in the class file; can be discarded by the VM at runtime

RetentionPolicy.RUNTIME

Stored in the class file; retained by the VM at runtime


As explained by the table, if you don't specify an @Retention annotation, the default behavior means that you probably won't be able to extract information on the annotation at runtime.[3] An example of RetentionPolicy.CLASS is the @Override annotation discussed in Lesson 9.

[3] The VM may choose to retain this information.

You will have the most need for RetentionPolicy.RUNTIME so that tools such as your TestRunner will be able to extract annotation information from their target classes. If you build tools that work directly with source code (for example, a plug-in for an IDE such as Eclipse), you can use RetentionPolicy.SOURCE to avoid unnecessarily storing annotation information in the class files. An example use might be an @Todo annotation used to mark sections of code that need attention.

To get reflection code to recognize @TestMethod annotations, you must modify the annotation type declaration:

 package sis.testing; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) public @interface TestMethod {} 

Your two TestRunnerTest tests should now pass:

 runAllTests:      [java] passed: 2 failed: 0 



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net