Java Annotation Default Values

In this chapter you will learn:

  1. Annotation Default Values
  2. Syntax for Java Annotation Default Values
  3. Example - How to use the default value from an annotation

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   w ww . j  a va2 s.com
@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  ww  . jav a 2  s . c om

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 ww. j  a v  a  2  s  . co  m*/

@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.

Next chapter...

What you will learn in the next chapter:

  1. How to create and use marker annotation in Java
  2. Example - Java Marker annotation
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