Package Annotations


Suppose you want the ability to designate packages as testing packages. Further, you want your testing tool to run "performancerelated" tests separately from other tests. In order to accomplish this, you can create an annotation whose target is a package. A test for this annotation:[4]

[4] Note use of the variable name pkg, since package is a keyword.


 @TestMethod public void packageAnnotations() {    Package pkg = this.getClass().getPackage();    TestPackage testPackage = pkg.getAnnotation(TestPackage.class);    assert testPackage.isPerformance(); } 

You extract annotation information from the Package object like you would from any other element object. You can obtain a Package object by sending the message getPackage to any Class object.

The annotation declaration is straightforward:

 package sis.testing; import java.lang.annotation.*; @Target(ElementType.PACKAGE) @Retention(RetentionPolicy.RUNTIME) public @interface TestPackage {    boolean isPerformance() default false; } 

However, the question is, Where does a package annotation go? Would it go before the package statement in every source file that belongs to the package? Or before just one of them? Or is it stored elsewhere?

Java limits you to at most one annotated package statement per package. This means that you can't just place an annotation before the package statement in an arbitrary source file.

The answer depends on which compiler you are using. Sun recommends a specific scheme that is based on a file system. Other compiler vendors may choose a different scheme. They may have to if the compile environment is not based on a file system.

The Sun scheme requires you to create a source file named package-info.java in the source directory that corresponds to the package you want to annotate. Sun's Java compiler reads this pseudosource file but produces no visible class files as output. (In fact, it is not possible to include a hyphen [-] in a class name.) This file should include any package annotations, followed by the appropriate package statement. You should not include anything else in package-info.java.

Here's what package-info.java might look like in the sis.testing package:

 @TestPackage(isPerformance=true) package sis.testing; 



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