Java: Creating New Annotations - dummies

Java: Creating New Annotations

By John Paul Mueller

You’ve seen comments used in many Java code examples. The compiler ignores comments, so when you create a comment you can write anything that you feel will be helpful later in figuring out what the application can do. Comments document your code.

However, there is another kind of documentation — the annotation. An annotation is a kind of documentation that the compiler also understands. When the compiler sees annotation in your code, it knows that it needs to do something special with the code that follows. Annotations are helpful in documenting your code in a functional way so that the compiler can help you enforce whatever documentation you provide.

The set of predefined annotations that come with Java are relatively limited in use. To create really useful annotations, you have to design them yourself or get them as part of a third-party package. Creating a new annotation is a three-step process:

  1. Add the appropriate import statement:

    import java.lang.annotation.*;
  2. Define an interface that describes the annotation to the compiler:

    // Create an annotation description.
    @Documented
    @interface AuthorData
    {
       String Name();
       String Date();
       double Version() default 1.0;
    }

    In this case, the annotation will appear in the documentation created by Javadoc because it includes the @Documented annotation. Every annotation description starts with the @interface keyword followed by the name of the annotation type, which is AuthorData in this case.

    Within the curly braces, you see the fields used to define the annotation data. This example includes Name, Date, and Version. The default keyword provides a value for a particular field. This means the field will use the value if it isn’t defined as part of the annotation in the application.

  3. Use the annotation in the application:

    @AuthorData
    (
       Name = "John Smythe", 
       Date = "04/01/2014"
    )

    The annotation appears before the element it affects, such as a class declaration. You must define each field that doesn’t have a default value. Optionally, you also define fields that do have a default value. In this case, the name of the author is John Smythe, and the code was last updated on 04/01/2014.