Single-Element Annotation Invokation

This section provides a tutorial example on how to use the shorthand format for a single annotation element named as 'value' in annotation invokation statements.

If an annotation invokation 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 invokation 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 invokation - All elements provided
   @Author(value="Herong", email="herong@nowhere.com")
   public static void main(String[] arg) {
      printMsg("Hello world!");
   }

   // Annotation invokation - One element provided
   @Author(value="John")
   public static void printMsg(String msg) {
      printMsgUpper(msg);
   }

   // Annotation invokation - 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

 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