Using Default Values : Annotations Types « Language « Java Tutorial






  1. Annotation default values is used if no value is specified.
  2. A default value is specified by adding a default clause.
  3. Default value must be of a type compatible with type.

Here is @MyAnnotation rewritten to include default values:

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
  String stringValue() default "defaultString";

  int intValue() default 101;
}

This declaration gives a default value of "Testing" to str and 9000 to val.

This means that neither value needs to be specified when @MyAnno is used.

However, either or both can be given values if desired.

Therefore, following are the four ways that @MyAnnotation can be used:

@MyAnnotation()                           // both str and val default
@MyAnnotation(stringValue = "some string")        // val defaults
@MyAnnotation(intValue = 100)                  // str defaults
@MyAnnotation(stringValue = "Testing", intValue = 100) // no defaults
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

// A simple annotation type.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
  String stringValue() default "defaultString";

  int intValue() default 101;
}

@MyAnnotation(stringValue = "for class", intValue = 100)
public class MainClass {
  // Annotate a method.
  @MyAnnotation(intValue = 100)
  public static void myMethod() {
  }

  public static void main(String[] arg) {
    try {
      MainClass ob = new MainClass();

      Method m = ob.getClass( ).getMethod("myMethod");
      Annotation[] annos = m.getAnnotations();

      System.out.println("All annotations for myMeth:");
      for(Annotation a : annos)
      System.out.println(a);

    } catch (Exception exc) {
    }
  }
}
All annotations for myMeth:
@MyAnnotation(intValue=100, stringValue=defaultString)








1.13.Annotations Types
1.13.1.Annotations and Annotation Types
1.13.2.The Annotation Interface
1.13.3.Using Default Values
1.13.4.Marker Annotations
1.13.5.Single-Member Annotations
1.13.6.Creates and uses a single-member annotation
1.13.7.The single-value syntax
1.13.8.Some Restrictions
1.13.9.A marker annotation