Annotation Targets


You have designed the @TestMethod annotation to be used by developers to mark test methods. Annotations can modify many other element types: types (classes, interfaces, and enums), fields, parameters, constructors, local variables, and packages. By default, you may use an annotation to modify any element. You can also choose to constrain an annotation type to modify one and only one element type. To do so, you supply an @Target meta-annotation on your annotation type declaration.

Since you didn't specify an @Target meta-annotation for @TestMethod, a developer could use the tag to modify any element, such as a field. Generally no harm would be done, but a developer could mark a field by accident, thinking that he or she marked a method. The test method would be ignored until someone noticed the mistake. Adding an @Target to an annotation type is one more step toward helping a developer at compile time instead of making him or her decipher later troubles.

Add the appropriate @Target meta-annotation to @TestMethod:

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

The parameter to @Target must be an ElementType enum, defined in java.lang.annotation. This enum supplies constants corresponding to the element types that an annotation type can modify: TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, and PACKAGE. There are special considerations for annotations with a target of ElementType.PACKAGE. See the section Package Annotations later in this lesson for more information.

To demonstrate what @Target does for your annotation types, modify TestRunnerTest. Instead of marking a method with @TestMethod, mark a field instead:

 // ... public class TestRunnerTest {    private @TestMethod TestRunner runner;    @TestMethod    public void singleMethodTest() {    // ... 

When you compile, you should see an error similar to the following:

 annotation type not applicable to this kind of declaration private @TestMethod TestRunner runner;          ^ 

Remove the extraneous annotation, recompile, and rerun your tests.



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