Annotation Default Values

In this chapter you will learn:

  1. Annotation Default Values
  2. How to use the default value from an annotation

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:

@Retention(RetentionPolicy.RUNTIME)//j a v  a  2  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

Use the default value from an annotation

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;
/*j av  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.

Next chapter...

What you will learn in the next chapter:

  1. How to create and use marker annotation in Java
Home » Java Tutorial » Annotations
Annotations
Annotation retention policy
Annotation reflection
Annotation Default Values
Marker annotation
Single-Member Annotations
Built-In Annotations