Annotation Default Values

You can give annotation members default values. Those default value are used if no value is specified when the annotation is applied.

A default value is specified by adding a default clause to a member's declaration.

It has this general form:

type member( ) default value;

Here is @MyAnno rewritten to include default values:

@interface MyAnno {
  String str() default "Testing";

  int val() default 9000;

Either or both can be given values if desired. Therefore, following are the four ways that @MyAnno can be used:

@MyAnno() // both str and val default 
@MyAnno(str = "string") // val defaults 
@MyAnno(val = 100) // str defaults 
@MyAnno(str = "Testing", val = 100) // no defaults

The following program demonstrates the use of 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 1;

public class Main {
  public static void myMeth() throws Exception{
    Main ob = new Main();
      Class c = ob.getClass();
      Method m = c.getMethod("myMeth");
      MyAnno anno = m.getAnnotation(MyAnno.class);
      System.out.println(anno.str() + " " + anno.val());

  public static void main(String args[]) throws Exception{
  Java Book 
    Language Basics  

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