Java - Annotation Element Default Value

Introduction

You can set a default value for an annotation type element.

The default value for an element can be specified using the following syntax:

<modifiers> @interface <annotation type name> { 
    <data-type> <element-name>() default <default-value>; 
} 
  

The default value must be of the type compatible to the data type for the element.

The following code sets a default value for its minor element.

  
@interface Version { 
        int major(); 
        int minor() default 0; // Set zero as default value for minor 
} 
  

Usage:

@Version(major=1) // minor is zero, which is its default value 
@Version(major=2) // minor is zero, which is its default value 
@Version(major=2, minor=1) // minor is 1, which is the specified value 
  

The following code shows how to specify default values for an array and other data types:

  
@interface My{ 
        double d() default 12.89; 
        int num() default 12; 
        int[] x() default {1, 2}; 
        String s() default "Hello"; 
        String[] s2() default {"abc", "xyz"}; 
        Class c() default Exception.class; 
        Class[] c2() default {Exception.class, java.io.IOException.class}; 
}