JMU
Annotations in Java
Some More Advanced Topics


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review
Defining Annotations
An Example

Defining an Annotation for the Javadoc Tool

import java.lang.annotation.*;

@Documented // Causes the data to be included in Javadoc documentation
@interface ClassComment
{
    String   author();
    String   date();
    String[] reviewers();
}
  
An Example (cont.)

Using an Annotation for the Javadoc tool

@ClassComment (
  author    = "David Bernstein",
  date      = "9/25/2017",
  reviewers = {"Chris Fox", "Nathan Sprague"}
)
  
Another Example

Defining an Annotation for Compile-Time Processing

/**
 * An annotation that can be used to indicate that a class
 * must have final attributes.
 * 
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
@Target(ElementType.TYPE)          // The annotation can be used anywhere a type is used
@Retention(RetentionPolicy.CLASS)  // Retained at compile-time; ignored at run-time
public @interface FinalAttributes 
{
  // No annotation type elements
}
  
A Third Example

Defining an Annotation for Run-Time Processing

import java.lang.annotation.*;

/**
 * An annotation that can be used to indicate that the test
 * is not critical (e.g., because the method being tested is a heuristic
 * that may not find an answer with the desired tolerance even though
 * it is working "correctly").
 * 
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
@Retention(RetentionPolicy.RUNTIME) //Retained at run-time
public @interface Noncritical
{
  /**
   * Return the optional description.
   * 
   * @return The description
   */
  String description() default "";
}
  
Processing Annotations