- Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
- Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
- Runtime processing — Some annotations are available to be examined at runtime.
@Author( name = "Benjamin Franklin", date = "3/27/2003" ) class MyClass() { }
@SuppressWarnings(value = "unchecked") void myMethod() { }
@SuppressWarnings("unchecked") void myMethod() { }
@Override void mySuperMethod() { }
Documentation
Many annotations replace what would otherwise have been comments in code. Suppose that a software group has traditionally begun the body of every class with comments providing important information:public class Generation3List extends Generation2List { // Author: John Doe // Date: 3/17/2002 // Current revision: 6 // Last modified: 4/12/2004 // By: Jane Doe // Reviewers: Alice, Bill, Cindy // class code goes here }
@interface ClassPreamble { String author(); String date(); int currentRevision() default 1; String lastModified() default "N/A"; String lastModifiedBy() default "N/A"; String[] reviewers(); // Note use of array }
interface
is preceded by the @ character (@ = "AT" as in Annotation Type). Annotation types are, in fact, a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces. The body of the annotation definition above contains annotation type element declarations, which look a lot like methods. Note that they may define optional default values. Once the annotation type has been defined, you can use annotations of that type, with the values filled in, like this:
@ClassPreamble ( author = "John Doe", date = "3/17/2002", currentRevision = 6, lastModified = "4/12/2004", lastModifiedBy = "Jane Doe", reviewers = {"Alice", "Bob", "Cindy"} // Note array notation ) public class Generation3List extends Generation2List { // class code goes here }
Note: To make the information in
@ClassPreamble
appear in Javadoc-generated documentation, you must annotate the @ClassPreamble
definition itself with the @Documented
annotation: import java.lang.annotation.*; // import this to use @Documented
@Documented
@interface ClassPreamble {
// Annotation element definitions
}
No comments:
Post a Comment