|
Java Developers Desk: Annotations |
|
II. Meta-Annotations (Annotation
Types):
There are four types of Meta annotations (or
annotations of annotations) defined by the
JDK 5. These are as follows:
- Target
- Retention
- Documented
- Inherited
1) Target annotation:
Target annotation specifies the elements of a
class to which annotation is to be applied. Here
is the listing of the elements of the enumerated
types as its value:
- @Target(ElementType.TYPE)— applicable to any element of a class.
- @Target(ElementType.FIELD)—applicable to field or property.
- @Target(ElementType.PARAMETER)—
applicable to the parameters of a
method.
- @Target(ElementType.LOCAL_VARIABLE)—
applicable to local variables.
- @Target(ElementType.METHOD)—
applicable to method level annotation.
- @Target(ElementType.CONSTRUCTOR)—
aplicable to constructors.
- @Target(ElementType.ANNOTATION_TYPE)—
specifies that the declared type itself is
an annotation type.
Here is an example that demonstrates the
target annotation:
Example:
@Target(ElementType.METHOD)
public @interface Test_Element {
public String doTestElement();
} |
|
|
Now lets create a class that use the
Test_Element annotation:
public class Test_Annotations {
public static void main(String arg[]) {
new Test_Annotations().doTestElement();
}
@Test_Target(doTestElement=”Hi ! How r
you”)
public void doTestElement() {
System.out.printf(“Testing Target Element
annotation”);
}} |
The @Target(ElementType.METHOD) specifies that this type of annotation can be
applied only at method level. Compiling and
running the above program will work properly.
Lets try to apply this type of annotation to
annotate an element:
public class Test_Annotations {
@Test_Target(doTestElement=”Hi! How r
you”)
private String str;
public static void main(String arg[]) {
new Test_Annotations().doTestElement();
}
public void doTestElement() {
System.out.printf(“Testing Target Element
annotation”);
}
}
Here we are trying to apply
@Target(ElementType.METHOD) at the
field level by declaring the element private
String str; after the
@Test_Target(doTestElement=”Hi ! How r
you”) statement.
On compiling this code will generate an error
like this:
“Test_Annotations.java”:
D:R_AND_DTest_Annotationsrctestmyannotation
Test_Annotations.java:16:
annotation type not applicable to this kind of
declaration at line
16, column 0 |
|
|
Jan 2008 | Java Jazz Up | 10 |
|
|
|
View All Topics |
All Pages of this Issue |
Pages:
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53 ,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63 ,
64,
65 ,
66 ,
67 ,
68 ,
69 ,
70 ,
71 ,
72 ,
73 ,
74 ,
75 ,
76 ,
77 ,
78 ,
79 ,
80 ,
81 ,
82 ,
83,
84 ,
85 ,
86,
87 ,
88,
89 ,
90 ,
91 ,
92 ,
93 ,
94 ,
95 ,
96 ,
97 ,
98 ,
99 ,
100 ,
101 ,
102 ,
103,
104 ,
105 ,
106,
107,
Download PDF |
|
|
|
|
|
|
|
|
|