Java Reference
In-Depth Information
You can use a compile-time constant expression to specify the value for an element of an annotation.
The following two instances of the Version annotation are valid, and have the same values for their elements:
@Version(major=2+1, minor=(int)13.2)
@Version(major=3, minor=13)
String Types
You can use an element of the String type in an annotation type. Listing 1-4 contains the code for an annotation type
called Name . It has two elements, first and last , which are of the String type.
Listing 1-4. Name Annotation Type, Which Has Two Elements, first and last, of the String Type
package com.jdojo.annotation;
public @interface Name {
String first();
String last();
}
The following snippet of code shows how to use the Name annotation type in a program:
@Name(first="John", last="Jacobs")
public class NameTest {
@Name(first="Wally", last="Inman")
public void aMethod() {
// More code goes here...
}
}
It is valid to use the string concatenation operator (+) in the value expression for an element of a String type. The
following two annotations are equivalent:
@Name(first="Jo" + "hn", last="Ja" + "cobs")
@Name(first="John", last="Jacobs")
The following use of the @Name annotation is not valid because the expression new String("John") is not a
compile-time constant expression:
@Name(first=new String("John"), last="Jacobs")
Class Types
The benefits of using the Class type as an element in an annotation type are not obvious. Typically, it is used where
a tool/framework reads the annotations with elements of a class type and performs some specialized processing on
the element's value or generates code. Let's go through a simple example of using a class type element. Suppose you
are writing a test runner tool for running test cases for a Java program. Your annotation will be used in writing test
cases. If your test case must throw an exception when it is invoked by the test runner, you need to use an annotation to
indicate that. Let's create a DefaultException class as shown in Listing 1-5.
 
Search WWH ::




Custom Search