0
# Code Structure Specifications
1
2
Builders for creating Java language constructs including classes, interfaces, enums, methods, fields, parameters, and annotations. All specifications use the Builder pattern for fluent construction.
3
4
## Capabilities
5
6
### TypeSpec
7
8
Specification for creating classes, interfaces, enums, and annotations. Handles modifiers, inheritance, generic type parameters, and member declarations.
9
10
```java { .api }
11
/**
12
* Specification for creating types (classes, interfaces, enums, annotations)
13
*/
14
public final class TypeSpec {
15
// Nested enum for type kinds
16
public enum Kind {
17
CLASS, INTERFACE, ENUM, ANNOTATION
18
}
19
20
// Public fields
21
public final Kind kind;
22
public final String name;
23
public final CodeBlock anonymousTypeArguments;
24
public final CodeBlock javadoc;
25
public final List<AnnotationSpec> annotations;
26
public final Set<Modifier> modifiers;
27
public final List<TypeVariableName> typeVariables;
28
public final TypeName superclass;
29
public final List<TypeName> superinterfaces;
30
public final Map<String, TypeSpec> enumConstants;
31
public final List<FieldSpec> fieldSpecs;
32
public final CodeBlock staticBlock;
33
public final CodeBlock initializerBlock;
34
public final List<MethodSpec> methodSpecs;
35
public final List<TypeSpec> typeSpecs;
36
public final List<Element> originatingElements;
37
public final Set<String> alwaysQualifiedNames;
38
39
// Static factory methods
40
public static Builder classBuilder(String name);
41
public static Builder classBuilder(ClassName className);
42
public static Builder interfaceBuilder(String name);
43
public static Builder interfaceBuilder(ClassName className);
44
public static Builder enumBuilder(String name);
45
public static Builder enumBuilder(ClassName className);
46
public static Builder anonymousClassBuilder(String typeArgumentsFormat, Object... args);
47
public static Builder anonymousClassBuilder(CodeBlock typeArguments);
48
public static Builder annotationBuilder(String name);
49
public static Builder annotationBuilder(ClassName className);
50
51
// Instance methods
52
public boolean hasModifier(Modifier modifier);
53
public Builder toBuilder();
54
public boolean equals(Object o);
55
public int hashCode();
56
public String toString();
57
}
58
```
59
60
**Usage Examples:**
61
62
```java
63
// Create a simple class
64
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
65
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
66
.build();
67
68
// Create an interface
69
TypeSpec processor = TypeSpec.interfaceBuilder("DataProcessor")
70
.addModifiers(Modifier.PUBLIC)
71
.addTypeVariable(TypeVariableName.get("T"))
72
.addMethod(MethodSpec.methodBuilder("process")
73
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
74
.addParameter(TypeVariableName.get("T"), "data")
75
.returns(TypeVariableName.get("T"))
76
.build())
77
.build();
78
79
// Create an enum
80
TypeSpec status = TypeSpec.enumBuilder("Status")
81
.addModifiers(Modifier.PUBLIC)
82
.addEnumConstant("PENDING")
83
.addEnumConstant("PROCESSING")
84
.addEnumConstant("COMPLETED")
85
.addEnumConstant("FAILED")
86
.build();
87
88
// Create an annotation
89
TypeSpec documented = TypeSpec.annotationBuilder("Documented")
90
.addModifiers(Modifier.PUBLIC)
91
.addMethod(MethodSpec.methodBuilder("value")
92
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
93
.returns(String.class)
94
.defaultValue("$S", "")
95
.build())
96
.build();
97
```
98
99
### MethodSpec
100
101
Specification for creating methods and constructors with parameters, return types, exceptions, and method bodies.
102
103
```java { .api }
104
/**
105
* Specification for creating methods and constructors
106
*/
107
public final class MethodSpec {
108
// Static constant for constructor name
109
public static final String CONSTRUCTOR = "<init>";
110
111
// Public fields
112
public final String name;
113
public final CodeBlock javadoc;
114
public final List<AnnotationSpec> annotations;
115
public final Set<Modifier> modifiers;
116
public final List<TypeVariableName> typeVariables;
117
public final TypeName returnType;
118
public final List<ParameterSpec> parameters;
119
public final boolean varargs;
120
public final List<TypeName> exceptions;
121
public final CodeBlock code;
122
public final CodeBlock defaultValue;
123
124
// Static factory methods
125
public static Builder methodBuilder(String name);
126
public static Builder constructorBuilder();
127
public static Builder overriding(ExecutableElement method);
128
public static Builder overriding(ExecutableElement method, DeclaredType enclosing, Types types);
129
130
// Instance methods
131
public boolean hasModifier(Modifier modifier);
132
public boolean isConstructor();
133
public Builder toBuilder();
134
public boolean equals(Object o);
135
public int hashCode();
136
public String toString();
137
}
138
```
139
140
**Usage Examples:**
141
142
```java
143
// Simple method
144
MethodSpec toString = MethodSpec.methodBuilder("toString")
145
.addAnnotation(Override.class)
146
.addModifiers(Modifier.PUBLIC)
147
.returns(String.class)
148
.addStatement("return $S", "Hello World")
149
.build();
150
151
// Method with parameters and exceptions
152
MethodSpec processFile = MethodSpec.methodBuilder("processFile")
153
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
154
.addParameter(Path.class, "file")
155
.addParameter(boolean.class, "createBackup")
156
.returns(void.class)
157
.addException(IOException.class)
158
.addException(IllegalArgumentException.class)
159
.addStatement("// Implementation here")
160
.build();
161
162
// Constructor
163
MethodSpec constructor = MethodSpec.constructorBuilder()
164
.addModifiers(Modifier.PUBLIC)
165
.addParameter(String.class, "name")
166
.addParameter(int.class, "age")
167
.addStatement("this.name = $N", "name")
168
.addStatement("this.age = $N", "age")
169
.build();
170
171
// Generic method
172
MethodSpec genericMethod = MethodSpec.methodBuilder("transform")
173
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
174
.addTypeVariable(TypeVariableName.get("T"))
175
.addTypeVariable(TypeVariableName.get("R"))
176
.addParameter(ParameterizedTypeName.get(List.class, TypeVariableName.get("T")), "input")
177
.addParameter(ParameterizedTypeName.get(Function.class, TypeVariableName.get("T"), TypeVariableName.get("R")), "mapper")
178
.returns(ParameterizedTypeName.get(List.class, TypeVariableName.get("R")))
179
.addStatement("return input.stream().map(mapper).collect($T.toList())", Collectors.class)
180
.build();
181
182
// Varargs method
183
MethodSpec format = MethodSpec.methodBuilder("format")
184
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
185
.returns(String.class)
186
.addParameter(String.class, "template")
187
.addParameter(ArrayTypeName.of(Object.class), "args")
188
.varargs()
189
.addStatement("return $T.format(template, args)", String.class)
190
.build();
191
```
192
193
### FieldSpec
194
195
Specification for creating class fields with types, modifiers, and initializers.
196
197
```java { .api }
198
/**
199
* Specification for creating fields
200
*/
201
public final class FieldSpec {
202
// Public fields
203
public final TypeName type;
204
public final String name;
205
public final CodeBlock javadoc;
206
public final List<AnnotationSpec> annotations;
207
public final Set<Modifier> modifiers;
208
public final CodeBlock initializer;
209
210
// Static factory methods
211
public static Builder builder(TypeName type, String name, Modifier... modifiers);
212
public static Builder builder(Type type, String name, Modifier... modifiers);
213
214
// Instance methods
215
public boolean hasModifier(Modifier modifier);
216
public Builder toBuilder();
217
public boolean equals(Object o);
218
public int hashCode();
219
public String toString();
220
}
221
```
222
223
**Usage Examples:**
224
225
```java
226
// Simple field
227
FieldSpec name = FieldSpec.builder(String.class, "name")
228
.addModifiers(Modifier.PRIVATE, Modifier.FINAL)
229
.build();
230
231
// Field with initializer
232
FieldSpec count = FieldSpec.builder(int.class, "count")
233
.addModifiers(Modifier.PRIVATE)
234
.initializer("0")
235
.build();
236
237
// Static constant
238
FieldSpec maxSize = FieldSpec.builder(int.class, "MAX_SIZE")
239
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
240
.initializer("$L", 1000)
241
.build();
242
243
// Complex initializer
244
FieldSpec items = FieldSpec.builder(
245
ParameterizedTypeName.get(List.class, String.class), "items")
246
.addModifiers(Modifier.PRIVATE, Modifier.FINAL)
247
.initializer("new $T<>()", ArrayList.class)
248
.build();
249
250
// Field with annotation
251
FieldSpec injected = FieldSpec.builder(DataService.class, "dataService")
252
.addModifiers(Modifier.PRIVATE)
253
.addAnnotation(Inject.class)
254
.build();
255
256
// Field with Javadoc
257
FieldSpec documented = FieldSpec.builder(String.class, "value")
258
.addModifiers(Modifier.PRIVATE)
259
.addJavadoc("The current value being processed.\n")
260
.addJavadoc("@see #getValue()\n")
261
.build();
262
```
263
264
### ParameterSpec
265
266
Specification for creating method and constructor parameters with types, names, and modifiers.
267
268
```java { .api }
269
/**
270
* Specification for creating parameters
271
*/
272
public final class ParameterSpec {
273
// Public fields
274
public final String name;
275
public final List<AnnotationSpec> annotations;
276
public final Set<Modifier> modifiers;
277
public final TypeName type;
278
public final CodeBlock javadoc;
279
280
// Static factory methods
281
public static ParameterSpec get(VariableElement element);
282
public static Builder builder(TypeName type, String name, Modifier... modifiers);
283
public static Builder builder(Type type, String name, Modifier... modifiers);
284
285
// Instance methods
286
public boolean hasModifier(Modifier modifier);
287
public Builder toBuilder();
288
public boolean equals(Object o);
289
public int hashCode();
290
public String toString();
291
}
292
```
293
294
**Usage Examples:**
295
296
```java
297
// Simple parameter
298
ParameterSpec name = ParameterSpec.builder(String.class, "name").build();
299
300
// Final parameter
301
ParameterSpec finalParam = ParameterSpec.builder(int.class, "value")
302
.addModifiers(Modifier.FINAL)
303
.build();
304
305
// Annotated parameter
306
ParameterSpec nullable = ParameterSpec.builder(String.class, "input")
307
.addAnnotation(Nullable.class)
308
.build();
309
310
// Generic parameter
311
ParameterSpec items = ParameterSpec.builder(
312
ParameterizedTypeName.get(List.class, WildcardTypeName.subtypeOf(Object.class)),
313
"items")
314
.build();
315
316
// Using in method
317
MethodSpec method = MethodSpec.methodBuilder("process")
318
.addParameter(ParameterSpec.builder(String.class, "input")
319
.addAnnotation(NonNull.class)
320
.addModifiers(Modifier.FINAL)
321
.build())
322
.addParameter(boolean.class, "validate")
323
.build();
324
```
325
326
### AnnotationSpec
327
328
Specification for creating annotations with member values.
329
330
```java { .api }
331
/**
332
* Specification for creating annotations
333
*/
334
public final class AnnotationSpec {
335
// Public fields
336
public final TypeName type;
337
public final Map<String, List<CodeBlock>> members;
338
339
// Static factory methods
340
public static AnnotationSpec get(Annotation annotation);
341
public static AnnotationSpec get(Annotation annotation, boolean includeDefaultValues);
342
public static AnnotationSpec get(AnnotationMirror annotation);
343
public static Builder builder(ClassName type);
344
public static Builder builder(Class<?> type);
345
346
// Instance methods
347
public Builder toBuilder();
348
public boolean equals(Object o);
349
public int hashCode();
350
public String toString();
351
}
352
```
353
354
**Usage Examples:**
355
356
```java
357
// Simple annotation
358
AnnotationSpec override = AnnotationSpec.builder(Override.class).build();
359
360
// Annotation with single value
361
AnnotationSpec suppressWarnings = AnnotationSpec.builder(SuppressWarnings.class)
362
.addMember("value", "$S", "unchecked")
363
.build();
364
365
// Annotation with multiple values
366
AnnotationSpec requestMapping = AnnotationSpec.builder(RequestMapping.class)
367
.addMember("value", "$S", "/api/users")
368
.addMember("method", "$T.GET", RequestMethod.class)
369
.addMember("produces", "$S", "application/json")
370
.build();
371
372
// Annotation with array values
373
AnnotationSpec multiValue = AnnotationSpec.builder(MyAnnotation.class)
374
.addMember("values", "$S", "first")
375
.addMember("values", "$S", "second")
376
.addMember("values", "$S", "third")
377
.build();
378
379
// Complex annotation with nested annotations
380
AnnotationSpec headers = AnnotationSpec.builder(Headers.class)
381
.addMember("value", "$L", AnnotationSpec.builder(Header.class)
382
.addMember("name", "$S", "Accept")
383
.addMember("value", "$S", "application/json")
384
.build())
385
.build();
386
387
// From existing annotation instance
388
@Deprecated
389
class ExistingClass { }
390
391
Annotation deprecatedAnnotation = ExistingClass.class.getAnnotation(Deprecated.class);
392
AnnotationSpec spec = AnnotationSpec.get(deprecatedAnnotation);
393
```
394
395
### Builder Patterns and Fluent APIs
396
397
All specification builders provide fluent method chaining:
398
399
```java
400
// Complex class with multiple members
401
TypeSpec userService = TypeSpec.classBuilder("UserService")
402
.addModifiers(Modifier.PUBLIC)
403
.addAnnotation(Service.class)
404
.addJavadoc("Service for managing user operations.\n")
405
.addJavadoc("@author Generated Code\n")
406
.addField(FieldSpec.builder(UserRepository.class, "repository")
407
.addModifiers(Modifier.PRIVATE, Modifier.FINAL)
408
.addAnnotation(Inject.class)
409
.build())
410
.addMethod(MethodSpec.constructorBuilder()
411
.addModifiers(Modifier.PUBLIC)
412
.addParameter(UserRepository.class, "repository")
413
.addStatement("this.repository = repository")
414
.build())
415
.addMethod(MethodSpec.methodBuilder("findById")
416
.addModifiers(Modifier.PUBLIC)
417
.addParameter(Long.class, "id")
418
.returns(ParameterizedTypeName.get(Optional.class, User.class))
419
.addStatement("return repository.findById(id)")
420
.build())
421
.build();
422
```
423
424
### Modifier Handling
425
426
All specifications support Java modifiers:
427
428
```java
429
// Checking for modifiers
430
if (methodSpec.hasModifier(Modifier.STATIC)) {
431
// Handle static method
432
}
433
434
// Common modifier combinations
435
Set<Modifier> publicStatic = EnumSet.of(Modifier.PUBLIC, Modifier.STATIC);
436
Set<Modifier> privateFinal = EnumSet.of(Modifier.PRIVATE, Modifier.FINAL);
437
438
// Modifier usage in builders
439
MethodSpec.methodBuilder("utility")
440
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
441
.build();
442
```