How to create and use annotation default values

Description

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

Syntax

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:


@Retention(RetentionPolicy.RUNTIME)/*from   www.jav  a 2 s. co  m*/
@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
/*from w w w.j av  a 2 s.c  o  m*/

Example

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;
/*from w  w  w.  ja  v a2 s . c om*/

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

  int val() default 1;
}

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

The code above generates the following result.





















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