Java Tutorial/Language/Annotations Create

Материал из Java эксперт
Перейти к: навигация, поиск

Creating Annotations

Annotation is created based on the interface.

  1. Adding "@" before the keyword interface to declare an annotation type.
  2. All annotations consist only method declarations.
  3. These methods act much like fields.

Our first annotation type:

// A simple annotation type.
@interface MyAnnotation {
  String stringValue();
  int intValue();

default values in an annotation.

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@interface MyAnno {
  String str() default "Testing";
  int val() default 9000;
class Meta3 {
  public static void myMeth() {
    Meta3 ob = new Meta3();
    try {
      Class c = ob.getClass();
      Method m = c.getMethod("myMeth");
      MyAnno anno = m.getAnnotation(MyAnno.class);
      System.out.println(anno.str() + " " + anno.val());
    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
  public static void main(String args[]) {

Define new annotation type

  1. All annotation types automatically extend the Annotation interface.
  2. Annotation is a super-interface of all annotations.
  3. It overrides hashCode( ), equals( ), and toString() defined by Object.
  4. It defines annotationType( ), which returns a Class object that represents the invoking annotation.
  5. When you apply an annotation, you give values to its members.

// A simple annotation type.
@interface MyAnnotation {
  String stringValue();
  int intValue();
public class MainClass {
  // Annotate a method.
  @MyAnnotation(stringValue = "Annotation Example", intValue = 100)
  public static void myMethod() {

Specifying a Retention Policy

A retention policy determines at what point an annotation is discarded.

  1. SOURCE: annotation retained only in the source file and is discarded during compilation.
  2. CLASS: annotation stored in the .class file during compilation, not available in the run time.
  3. RUNTIME: annotation stored in the .class file and available in the run time.
  4. They are defined java.lang.annotation.RetentionPolicy enumeration.

A retention policy is specified using Java"s built-in annotations: @Retention.