Single-Member Annotations

A single-member annotation contains only one member. It allows a shorthand form of specifying the value of the member.

When only one member is present, you don't need to specify the name of the member.

In order to use this shorthand, the name of the member must be value. Here is an example that creates and uses a single-member annotation:


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


@Retention(RetentionPolicy.RUNTIME)
@interface MySingle {
  int value(); // this variable name must be value
}

public class Main {
  @MySingle(100)
  public static void myMeth() {
    Main ob = new Main ();
    try {
      Method m = ob.getClass().getMethod("myMeth");
      MySingle anno = m.getAnnotation(MySingle.class);
      System.out.println(anno.value()); // displays 100
    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }

  public static void main(String args[]) {
    myMeth();
  }
}

You can use the single-value syntax when applying an annotation that has other members, but those other members must all have default values.

For example, here the value xyz is added, with a default value of zero:


@interface SomeAnno { 
    int value(); 
    int xyz() default 0; 
}

You can apply @SomeAnno as ,


@SomeAnno(1)

by specifying the value using the single-member syntax.

In this case, xyz defaults to zero, and value gets the value 1.

Home 
  Java Book 
    Language Basics  

Annotations:
  1. Annotations (Metadata)
  2. Retention Policy
  3. Annotation Default Values
  4. Marker Annotations
  5. Single-Member Annotations
  6. Built-In Annotations