Java Tutorials - Herong's Tutorial Examples - v8.22, by Herong Yang
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 invocation 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 invocation - All values provided @Header(usage="Entry point", version=1, author="Herong") public static void main(String[] arg) { printMsg("Hello world!"); } // Annotation invocation - 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
Execution Process, Entry Point, Input and Output
Primitive Data Types and Literals
Bits, Bytes, Bitwise and Shift Operations
Managing Bit Strings in Byte Arrays
Reference Data Types and Variables
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
►Default Values for Annotation Elements
Single-Element Annotation Invocation
No-Element (Marker) Annotation Invocation