1.11.1Creating 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.

注解基于接口被创建.

在关键字 interface 前加'@'来声明一个annotation类型.

注解只包含方法声明.

这些方法的行为类似字段.

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

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() {
  }

}

 

1.11.3 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.

 

@Retention(retention-policy)

the default policy is CLASS.

 

 

MyAnnotation uses @Retention to specify the RUNTIME retention policy.

 

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

// A simple annotation type.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
  String stringValue();

  int intValue();
}

public class MainClass {
  // Annotate a method.
  @MyAnnotation(stringValue = "Annotation Example", intValue = 100)
  public static void myMethod() {
  }

}

 1.11.4 default values in an annotation 注解中的默认值

 

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str() default "Testing";

  int val() default 9000;
}

public  class Meta3 {
  @MyAnno()
  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[]) {
    myMeth();
  }
}