Java - Annotation Annotation Shorthand

Introduction

Suppose you have an annotation type called Enabled:

@interface Enabled {
        boolean status() default true;
}

Enabled annotation can be used in either of the following two forms:

@Enabled
class Test {
}

@Enabled()
class Test {
}

If an annotation type has only one element with named value, you can omit the name from name=value pair from your annotation.

The following code declares a Company annotation type, which has only one element named value:

@interface Company {
   String value(); // the element name is value
}

You can omit the name from name=value pair.

@Company("Abc Inc.")
public class Test {
        // Code goes here
}

Array short hand

Let's consider the following annotation type called Reviewers:

@interface Reviewers {
   String[] value(); // the element name is value
}

Usage

// No need to specify name of the element
@Reviewers({"A", "B"})
class Test {
}

You can omit the braces if you specify only one element in the array for the value element of the Reviewers annotation type.

@Reviewers("A")
class Test {
}