Java Single-Member Annotations

In this chapter you will learn:

  1. How to create and use single member annotation
  2. Example - Java Single-Member Annotations
  3. How to set a default value for a member in an annotation

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;
//  ww  w.j av a 2s  . 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.

Next chapter...

What you will learn in the next chapter:

  1. What are built-in annotations
  2. @Retention
  3. @Documented
  4. @Target
  5. @Inherited
  6. @Override
  7. @Deprecated
  8. @SuppressWarnings
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