- Forward


Annotations in Java
Some More Advanced Topics


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Review
Back SMYC Forward
  • Purpose:
    • Annotations provide information/data about a program
  • Types:
    • Declaration Annotations
    • Type Annotations
    • Annotation Annotations
Defining Annotations
Back SMYC Forward
  • Syntax of the Declaration:
    • Like an interface but with an opening @
  • Contents:
    • Annotation type element declarations (which look like methods but can define default values)
An Example
Back SMYC Forward

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.)
Back SMYC Forward

Using an Annotation for the Javadoc tool

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

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
Back SMYC Forward

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
Back SMYC Forward
  • At Compile-Time:
    • Involves the use of a Processor
  • At Run-Time:
    • Involves the use of reflection
There's Always More to Learn
Back -