Default Values for Annotation Elements

This section provides a tutorial example on how to declare default values for annotation elements and how to use default values in annotation invokation statements.

When you declare an annotation type, you can provide default values for annotation elements. The default value is specified at the end of the element declaration and follows the keyword "default"

When you invoke an annotation type that has an element with a default value, you can take the default value by skipping this element in the argument list.

Here is a sample program that shows you how to declare and use annotation element default values.

/* DefaultValueAnnotation.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
class DefaultValueAnnotation {

   // Annotation declaration
   @interface Header {
      String usage();    // Usage of the targeted construct
      int version();     // Version number of targeted construct
      String author() default "Unknown"; // Default value provided
   }

   // Annotation invokation - All values provided
   @Header(usage="Entry point", version=1, author="Herong")
   public static void main(String[] arg) {
      printMsg("Hello world!");
   }

   // Annotation invokation - Default value used
   @Header(usage="Display message", version=10)
   public static void printMsg(String msg) {
      System.out.println(msg);
   }
}

If you compile and run the program, you will get:

herong> java DefaultValueAnnotation.java

Hello world!

Table of Contents

 About This Book

 JDK - Java Development Kit

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Control Flow Statements

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

 Reference Data Types and Variables

 Enum Types and Enum Constants

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

 Generic Classes and Parameterized Types

 Generic Methods and Type Inference

 Lambda Expressions and Method References

 Java Modules - Java Package Aggregation

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 Assert Statements and -ea" Option

Annotation Statements and Declarations

 What Is Annotation

 Use "interface" as Annotation

Default Values for Annotation Elements

 Single-Element Annotation Invokation

 No-Element (Marker) Annotation Invokation

 getAnnotations() Method - Annotation APIs

 Predefined Annotation Types

 Java Related Terminologies

 Outdated Tutorials

 References

 Full Version in PDF/EPUB