Java Annotations

In this chapter you will learn:

  1. What is annotation and how to create an annotation
  2. Syntax to create Java Annotations
  3. Note for Java Annotations

Description

Annotations embeds supplemental information into a source file. An annotation does not change the semantics of a program.

Syntax

An annotation is created through a mechanism based on the interface.

The following code declares an annotation called MyAnno:


// A simple annotation type. 
@interface MyAnno {
  String str();//from   ww w. j ava 2  s.  com

  int val();
}

@ precedes the keyword interface. All annotations have method declarations only. An annotation cannot include an extends clause.

Note

All annotation types automatically extend the Annotation interface. Annotation interface is a super-interface of all annotations. Annotation interface is declared within the java.lang.annotation package.

Any type of declaration can have an annotation associated with it. For example, classes, methods, fields, parameters, and enum constants can be annotated. An annotation can be annotated as well. In all cases, the annotation precedes the rest of the declaration.

When you apply an annotation, you give values to its members. For example, here is an example of MyAnno being applied to a class:


// Annotate a method. 
@MyAnno(str = "Annotation Example", val = 100) 
public class Main{}

This annotation is linked with the class Main.

Next chapter...

What you will learn in the next chapter:

  1. Retention Policy
  2. Retention level
  3. Syntax for Java Annotation retention
  4. Example - Retention Policy.RUNTIME
  5. Example - How to obtaining Annotations at Run Time by Use of Reflection
Home »
  Java Tutorial »
    Java Langauge »
      Java Annotations
Java Annotations
Java Annotation retention policy
Java Annotation reflection
Java Annotation Default Values
Java Marker annotation
Java Single-Member Annotations
Java Built-In Annotations