- Forward


Annotations in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

The Basics
Back SMYC Forward
  • Purpose:
    • Annotations provide information/data about a program (that is not part of the program itself)
  • An Implication:
    • Annotations do not have any impact on the program itself
Who/What Might Use Annotations
Back SMYC Forward
  • Programmers and Reviewers/Inspectors:
    • To detect defects
  • Compiler:
    • To detect defects
    • To suppress messages
  • Other Programs:
    • For many purposes
Kinds of Uses
Back SMYC Forward
  • Construction:
    • Improve code quality (e.g., the @Override annotation)
  • Design:
    • Provide features that are difficult to provide in other ways (e.g., the @Test annotation makes it possible for JUnit to easily identify tests without using method names)
  • Testing:
    • Weight the importance of different tests
Syntax
Back SMYC Forward
  • Basic:
    • @Entity
  • With Elements:
    • @Entity (name1 = "value1", name2 = "value2", ...)
  • With a Single Unnamed Element:
    • @Entity ("value")
Allowed Locations
Back SMYC Forward
  • Declaration Annotations:
    • On declarations of classes, attributes, methods, and variables
  • Type Annotations:
    • On the new operator
    • On type casts
    • On throws clauses
    • On implements clauses
    • Anywhere you can use a type
  • Annotation Annotations:
    • On another annotation
Some Predefined Annotations
Back SMYC Forward
  • Declaration Annotations:
    • @Deprecated indicates the member should no longer be used and will cause the compiler to generate a warning if it is
    • @Override indicates the method should be overriding a method in a super class and will cause the compiler to generate an error if it isn't
    • @SuppressWarnings tells the compiler to suppress warnings in a specific category ("unchecked" and or "deprecated")
  • Type Annotations:
    • None exist - you must develop or acquire a checking framework that defines them
  • Annotation Annotations:
    • @Documented indicates that the annotation should be included in Javadoc documentation
    • @Retention indicates how the annotation should be stored (i.e., SOURCE, CLASS, or RUNTIME)
    • @Target indicates the Java elements the annotation can be applied to
There's Always More to Learn
Back -