Java Tutorials - Herong's Tutorial Examples - v8.22, by Herong Yang
Single-Element Annotation Invocation
This section provides a tutorial example on how to use the shorthand format for a single annotation element named as 'value' in annotation invocation statements.
If an annotation invocation statement only has a single annotation element and the element name is "value", you can specify the element value without the element name in the argument list.
So the following two statements are the same, if @Author annotation has an element called "value" and other elements have default values.
@Author(value="Herong") class X {...} // Shorthand format of the above @Author("Herong") class X {...}
Here is a sample program that shows you how to use the shorthand format for a single annotation element named as "value" in annotation invocation statements.
/* SingleElementAnnotation.java * Copyright (c) HerongYang.com. All Rights Reserved. */ class SingleElementAnnotation { // Annotation declaration @interface Author { String value() default "Unknown"; // Special element String email() default "info@nowhere.com"; } // Annotation invocation - All elements provided @Author(value="Herong", email="herong@nowhere.com") public static void main(String[] arg) { printMsg("Hello world!"); } // Annotation invocation - One element provided @Author(value="John") public static void printMsg(String msg) { printMsgUpper(msg); } // Annotation invocation - One value only @Author(value="Mary") public static void printMsgUpper(String msg) { System.out.println(msg.toUpperCase()); } }
If you compile and run the program, you will get:
herong> java SingleElementAnnotation.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