-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathTypeAnnoDemo.java
More file actions
100 lines (73 loc) · 2.49 KB
/
TypeAnnoDemo.java
File metadata and controls
100 lines (73 loc) · 2.49 KB
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
package chapter12;
//Demonstrate several type annotations
import java.lang.annotation.*;
import java.lang.reflect.*;
//A marker annotation that can be applied to a type
@Target(ElementType.TYPE_USE)
@interface TypeAnno{}
//Another marker annotation that can be applied to a type
@Target(ElementType.TYPE_USE)
@interface NotZeroLen{}
//Still another marker annotation that can be applied to a type
@Target(ElementType.TYPE_USE)
@interface Unique{}
//A parameterized annotation that can be applied to a type
@Target(ElementType.TYPE_USE)
@interface MaxLen{
int value();
}
//An annotation that can be applied to a type parameter
@Target(ElementType.TYPE_PARAMETER)
@interface What2{
String description();
}
//An annotation that can be applied to a field declaration
@Target(ElementType.FIELD)
@interface EmptyOk{}
//An annotation that can be applied to a method declaration
@Target(ElementType.METHOD)
@interface Recommended{}
//Use annotation on a type parameter
public class TypeAnnoDemo<@What2(description = "Generic data type") T> {
//Use a type annotation on a constructor
public @Unique TypeAnnoDemo(){}
//Annotate the type (in this case string ),not the field
@TypeAnno String str;
//This annotates the field test
@EmptyOk String test;
//Use a type annotation to annotate this (the receiver)
public int f(@TypeAnno TypeAnnoDemo<T> this,int x ){
return 10;
}
//Annotate the return type
public @TypeAnno Integer f2(int j,int k){
return j+k;
}
//Annotate the method declaration
public @Recommended Integer f3(String str){
return str.length()/2;
}
//Use a type annotation with a throws clause
public void f4() throws @TypeAnno NullPointerException{
//...
}
//Annotate array levels
String @MaxLen(10) [] @NotZeroLen [] w;
//Annotate the array element type
@TypeAnno Integer[] vec;
public static void myMeth(int i){
//Use a type annotation on a type argument
TypeAnnoDemo<@TypeAnno Integer> ob=new TypeAnnoDemo<@TypeAnno Integer>();
//Use a type annotation with new
@Unique TypeAnnoDemo<Integer>ob2= new @Unique TypeAnnoDemo<Integer>();
Object x = Integer.valueOf(10);
Integer y;
//Use type annotation on a cast
y=(@TypeAnno Integer)x;
}
public static void main(String[] args) {
myMeth(10);
}
//Use type annotation with inheritance clause
class SomeClass extends @TypeAnno TypeAnnoDemo<Boolean>{}
}