Java Reference
In-Depth Information
If you want to annotate a program element with the
Enabled
annotation type using the default value for its
element, you can use the
@Enabled()
syntax. You do not need to specify the values for
the status
element because
it has a default value. You can use shorthand in this situation, which allows you to omit the parentheses. You can just
use
@Enabled
instead of using
@Enabled()
. The
Enabled
annotation can be used in either of the following two forms:
@Enabled
public class Test {
// Code goes here
}
@Enabled()
public class Test {
// Code goes here
}
An annotation type with only one element also has a shorthand syntax. You can use this shorthand as long as
you adhere to a naming rule for the sole element in the annotation type. The name of the element must be
value
. If
an annotation type has only one element that is named
value
, you can omit the name from
name=value
pair from
your annotation. The following snippet of code declares a
Company
annotation type, which has only one element
named
value
:
public @interface Company {
String value(); // the element name is value
}
You can omit the name from
name=value
pair when you use the
Company
annotation, as shown below. If you want
to use the element name with the
Company
annotation, you can always do so as
@Company(value="Abc Inc.")
.
@Company("Abc Inc.")
public class Test {
// Code goes here
}
You can use this shorthand of omitting the name of the element from annotations, even if the element data type
is an array. Let's consider the following annotation type called
Reviewers
:
public @interface Reviewers {
String[] value(); // the element name is value
}
Since the
Reviewers
annotation type has only one element, which is named
value
, you can omit the element
name when you are using it.
// No need to specify name of the element
@Reviewers({"John Jacobs", "Wally Inman"})
public class Test {
// Code goes here
}