THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

public void badMethod() { / ... / }


Otherwise, for each element that does not have a default value you must list an initializer, of the form
name=value, as you have seen with ClassInfo. The order of initializers is not significant, but each
element can only appear once. If an element has a default value then it need not appear, but you can include it
if you want to override the default value with a specific one, as you saw in the Revision annotation type
with ClassInfo.


If an element has an array type, then it is initialized with an array initializer expression. For example, an
annotation to track the bug fixes applied to a class might look like this:


@interface BugsFixed {
String[] bugIDs();
}


The intent is that as each bug is fixed, its identifier is appended to the initializer list for bugIDs. Here's how
it might be used:


@BugsFixed(bugIDs = { "457605", "532456"})
class Foo { / ... / }


If an array has only a single element, then you can use a shorthand to initialize the array, dispensing with the
braces around the array elements. For example, the first bug fixed in Foo could be annotated like this:


@BugsFixed(bugIDs = "457605")


If an annotation type, like BugsFixed, has only a single element, then naming that element value allows
for some additional shorthand:


@interface BugsFixed {
String[] value();
}


The first use of BugsFixed above can now be written simply as


@BugsFixed({ "457605", "532456"})


If there is a single initializer expression, then it is assumed to initialize an element called value. If there is no
such element by that name, then you will get a compile-time error. Combining this shorthand with the
shorthand for arrays with one element, you can rewrite the second use of BugsFixed to be


@BugsFixed("457605")

Free download pdf