0
# Type System
1
2
Type representation system for Java including primitive types, class names, and basic type operations. This forms the foundation for all type references in JavaPoet.
3
4
## Capabilities
5
6
### TypeName
7
8
Base class for all type representations in JavaPoet. Provides common type operations and constants for primitive types.
9
10
```java { .api }
11
/**
12
* Base class for all type representations
13
*/
14
public class TypeName {
15
// Primitive type constants
16
public static final TypeName VOID;
17
public static final TypeName BOOLEAN;
18
public static final TypeName BYTE;
19
public static final TypeName SHORT;
20
public static final TypeName INT;
21
public static final TypeName LONG;
22
public static final TypeName CHAR;
23
public static final TypeName FLOAT;
24
public static final TypeName DOUBLE;
25
public static final ClassName OBJECT;
26
27
// Public fields
28
public final List<AnnotationSpec> annotations;
29
30
// Factory methods
31
public static TypeName get(TypeMirror mirror);
32
public static TypeName get(Type type);
33
34
// Annotation methods
35
public TypeName annotated(AnnotationSpec... annotations);
36
public TypeName annotated(List<AnnotationSpec> annotations);
37
public TypeName withoutAnnotations();
38
public boolean isAnnotated();
39
40
// Type classification methods
41
public boolean isPrimitive();
42
public boolean isBoxedPrimitive();
43
44
// Boxing/unboxing operations
45
public TypeName box();
46
public TypeName unbox();
47
48
// Standard object methods
49
public boolean equals(Object o);
50
public int hashCode();
51
public String toString();
52
}
53
```
54
55
**Usage Examples:**
56
57
```java
58
// Using primitive type constants
59
MethodSpec getter = MethodSpec.methodBuilder("getCount")
60
.returns(TypeName.INT)
61
.addStatement("return count")
62
.build();
63
64
// Boxing and unboxing
65
TypeName primitiveInt = TypeName.INT;
66
TypeName boxedInt = primitiveInt.box(); // Integer
67
TypeName backToPrimitive = boxedInt.unbox(); // int
68
69
// Type classification
70
if (someType.isPrimitive()) {
71
// Handle primitive type
72
}
73
if (someType.isBoxedPrimitive()) {
74
// Handle boxed primitive (Integer, Boolean, etc.)
75
}
76
77
// Creating types from reflection
78
TypeName stringType = TypeName.get(String.class);
79
TypeName listType = TypeName.get(List.class);
80
81
// Annotated types
82
TypeName annotatedString = TypeName.get(String.class)
83
.annotated(AnnotationSpec.builder(NonNull.class).build());
84
```
85
86
### ClassName
87
88
Represents declared class, interface, or annotation type names. Provides methods for working with package names, nested classes, and type hierarchies.
89
90
```java { .api }
91
/**
92
* Represents declared class, interface, or annotation type names
93
*/
94
public final class ClassName extends TypeName implements Comparable<ClassName> {
95
// Static constants
96
public static final ClassName OBJECT;
97
98
// Factory methods
99
public static ClassName get(Class<?> clazz);
100
public static ClassName bestGuess(String classNameString);
101
public static ClassName get(String packageName, String simpleName, String... simpleNames);
102
public static ClassName get(TypeElement element);
103
104
// Annotation methods (override parent)
105
public ClassName annotated(List<AnnotationSpec> annotations);
106
public ClassName withoutAnnotations();
107
108
// Name component methods
109
public String packageName();
110
public String simpleName();
111
public List<String> simpleNames();
112
public String canonicalName();
113
public String reflectionName();
114
115
// Hierarchy methods
116
public ClassName enclosingClassName();
117
public ClassName topLevelClassName();
118
119
// Related class methods
120
public ClassName peerClass(String name);
121
public ClassName nestedClass(String name);
122
123
// Comparable implementation
124
public int compareTo(ClassName o);
125
}
126
```
127
128
**Usage Examples:**
129
130
```java
131
// Creating class names from Class objects
132
ClassName stringClass = ClassName.get(String.class);
133
ClassName listClass = ClassName.get(List.class);
134
ClassName mapEntryClass = ClassName.get(Map.Entry.class);
135
136
// Creating class names from package and name components
137
ClassName myClass = ClassName.get("com.example", "MyClass");
138
ClassName nestedClass = ClassName.get("com.example", "Outer", "Inner");
139
140
// Best guess parsing (use with caution)
141
ClassName guessedClass = ClassName.bestGuess("com.example.MyClass");
142
143
// Working with nested classes
144
ClassName outerClass = ClassName.get("com.example", "Outer");
145
ClassName innerClass = outerClass.nestedClass("Inner"); // com.example.Outer.Inner
146
ClassName peerClass = innerClass.peerClass("Sibling"); // com.example.Sibling
147
148
// Extracting name components
149
System.out.println(mapEntryClass.packageName()); // "java.util"
150
System.out.println(mapEntryClass.simpleName()); // "Entry"
151
System.out.println(mapEntryClass.canonicalName()); // "java.util.Map.Entry"
152
System.out.println(mapEntryClass.reflectionName()); // "java.util.Map$Entry"
153
154
// Hierarchy navigation
155
ClassName entry = ClassName.get(Map.Entry.class);
156
ClassName map = entry.enclosingClassName(); // java.util.Map
157
ClassName topLevel = entry.topLevelClassName(); // java.util.Map
158
```
159
160
### Type Creation from Reflection
161
162
JavaPoet can create type representations from Java reflection types:
163
164
```java
165
// From Class objects
166
TypeName stringType = TypeName.get(String.class);
167
TypeName intType = TypeName.get(int.class);
168
TypeName voidType = TypeName.get(void.class);
169
170
// From generic reflection types
171
Method method = MyClass.class.getMethod("process", List.class);
172
Type returnType = method.getGenericReturnType();
173
TypeName returnTypeName = TypeName.get(returnType);
174
175
// From field types
176
Field field = MyClass.class.getField("items");
177
TypeName fieldType = TypeName.get(field.getGenericType());
178
```
179
180
### Type Creation from javax.lang.model
181
182
For annotation processing, JavaPoet integrates with javax.lang.model types:
183
184
```java
185
// From TypeMirror (annotation processing)
186
@Override
187
public boolean process(Set<? extends TypeElement> annotations,
188
RoundEnvironment roundEnv) {
189
for (Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) {
190
TypeMirror typeMirror = element.asType();
191
TypeName typeName = TypeName.get(typeMirror);
192
193
// Use typeName in code generation...
194
}
195
return true;
196
}
197
198
// From TypeElement
199
TypeElement classElement = processingEnv.getElementUtils()
200
.getTypeElement("com.example.MyClass");
201
ClassName className = ClassName.get(classElement);
202
```
203
204
### Type Annotations
205
206
All TypeName instances support type annotations:
207
208
```java
209
// Single annotation
210
TypeName annotatedString = ClassName.get(String.class)
211
.annotated(AnnotationSpec.builder(NonNull.class).build());
212
213
// Multiple annotations
214
TypeName multiAnnotated = TypeName.INT
215
.annotated(
216
AnnotationSpec.builder(Range.class)
217
.addMember("min", "0")
218
.addMember("max", "100")
219
.build(),
220
AnnotationSpec.builder(NonNegative.class).build()
221
);
222
223
// Remove annotations
224
TypeName withoutAnnotations = annotatedString.withoutAnnotations();
225
226
// Check for annotations
227
if (someType.isAnnotated()) {
228
List<AnnotationSpec> annotations = someType.annotations;
229
// Process annotations...
230
}
231
```
232
233
### Type Comparison and Equality
234
235
```java
236
// Type equality
237
TypeName type1 = TypeName.get(String.class);
238
TypeName type2 = ClassName.get(String.class);
239
boolean equal = type1.equals(type2); // true
240
241
// ClassName comparison (implements Comparable)
242
ClassName class1 = ClassName.get("com.example", "A");
243
ClassName class2 = ClassName.get("com.example", "B");
244
int comparison = class1.compareTo(class2); // negative value
245
246
// Sorting class names
247
List<ClassName> classNames = Arrays.asList(
248
ClassName.get("z.example", "Last"),
249
ClassName.get("a.example", "First")
250
);
251
Collections.sort(classNames); // Sorts by canonical name
252
```
253
254
### Working with Object Types
255
256
```java
257
// The universal Object type
258
ClassName objectType = ClassName.OBJECT; // java.lang.Object
259
TypeName objectTypeName = TypeName.OBJECT; // Same as above
260
261
// Checking if a type extends Object (all reference types do)
262
boolean extendsObject = !someType.isPrimitive(); // true for all reference types
263
264
// Using Object in method signatures
265
MethodSpec method = MethodSpec.methodBuilder("process")
266
.addParameter(TypeName.OBJECT, "item")
267
.returns(TypeName.OBJECT)
268
.addStatement("return processItem(item)")
269
.build();
270
```