How to create and use Single-Member Annotations in Java

Description

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.

Example

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;
//  w  w  w  .j a  v a2s.c om

@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();
  }
}

The code above generates the following result.

Example 2

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 Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures