0
# JavaPoet
1
2
JavaPoet is a Java API for generating `.java` source files programmatically. It provides a fluent builder API that enables developers to create Java classes, methods, fields, and other code constructs dynamically at runtime or during compilation phases like annotation processing. The library offers immutable model objects for representing Java language elements and handles proper formatting, indentation, imports, and Java syntax rules automatically.
3
4
## Package Information
5
6
- **Package Name**: javapoet
7
- **Package Type**: maven
8
- **Group ID**: com.squareup
9
- **Language**: Java
10
- **Installation**: Add to `pom.xml`:
11
```xml
12
<dependency>
13
<groupId>com.squareup</groupId>
14
<artifactId>javapoet</artifactId>
15
<version>1.13.0</version>
16
</dependency>
17
```
18
- **Gradle**: `implementation 'com.squareup:javapoet:1.13.0'`
19
20
## Core Imports
21
22
```java
23
import com.squareup.javapoet.*;
24
```
25
26
Specific imports for common classes:
27
28
```java
29
import com.squareup.javapoet.JavaFile;
30
import com.squareup.javapoet.TypeSpec;
31
import com.squareup.javapoet.MethodSpec;
32
import com.squareup.javapoet.FieldSpec;
33
import com.squareup.javapoet.ParameterSpec;
34
import com.squareup.javapoet.AnnotationSpec;
35
import com.squareup.javapoet.CodeBlock;
36
import com.squareup.javapoet.ClassName;
37
import com.squareup.javapoet.TypeName;
38
import javax.lang.model.element.Modifier;
39
```
40
41
## Basic Usage
42
43
```java
44
import com.squareup.javapoet.*;
45
import javax.lang.model.element.Modifier;
46
47
// Create a method
48
MethodSpec main = MethodSpec.methodBuilder("main")
49
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
50
.returns(void.class)
51
.addParameter(String[].class, "args")
52
.addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
53
.build();
54
55
// Create a class containing the method
56
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
57
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
58
.addMethod(main)
59
.build();
60
61
// Create a Java file containing the class
62
JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld)
63
.build();
64
65
// Write to system output or file
66
javaFile.writeTo(System.out);
67
```
68
69
## Architecture
70
71
JavaPoet is built around several key design patterns:
72
73
- **Builder Pattern**: All specification classes (TypeSpec, MethodSpec, FieldSpec, etc.) use builders for fluent construction
74
- **Immutable Objects**: All generated specifications are immutable once built, ensuring thread safety
75
- **Template System**: CodeBlock uses template strings with placeholders (`$L`, `$S`, `$T`, `$N`) for safe code generation
76
- **Type Safety**: Extensive use of generics and type parameters for compile-time safety
77
- **Automatic Import Management**: Handles Java imports automatically based on referenced types
78
79
## Capabilities
80
81
### File and Package Management
82
83
Core functionality for creating and writing Java source files with proper package structure and import management.
84
85
```java { .api }
86
public final class JavaFile {
87
// Static factory method
88
public static Builder builder(String packageName, TypeSpec typeSpec);
89
90
// Writing methods
91
public void writeTo(Appendable out) throws IOException;
92
public void writeTo(Path directory) throws IOException;
93
public Path writeToPath(Path directory) throws IOException;
94
public void writeTo(File directory) throws IOException;
95
public void writeTo(Filer filer) throws IOException;
96
public JavaFileObject toJavaFileObject();
97
}
98
```
99
100
[File Management](./file-management.md)
101
102
### Type System
103
104
Type representation system including basic types, class names, parameterized types, arrays, type variables, and wildcards.
105
106
```java { .api }
107
// Base type class
108
public class TypeName {
109
// Type constants
110
public static final TypeName VOID;
111
public static final TypeName BOOLEAN;
112
public static final TypeName INT;
113
public static final TypeName LONG;
114
// ... other primitives
115
116
// Factory methods
117
public static TypeName get(TypeMirror mirror);
118
public static TypeName get(Type type);
119
120
// Type operations
121
public TypeName annotated(AnnotationSpec... annotations);
122
public boolean isPrimitive();
123
public TypeName box();
124
public TypeName unbox();
125
}
126
127
// Class names
128
public final class ClassName extends TypeName implements Comparable<ClassName> {
129
public static ClassName get(Class<?> clazz);
130
public static ClassName get(String packageName, String simpleName, String... simpleNames);
131
public String packageName();
132
public String simpleName();
133
public ClassName nestedClass(String name);
134
}
135
```
136
137
[Type System](./type-system.md)
138
139
### Code Structure Specifications
140
141
Builders for creating Java language constructs including classes, interfaces, enums, methods, fields, and parameters.
142
143
```java { .api }
144
// Type specification
145
public final class TypeSpec {
146
public static Builder classBuilder(String name);
147
public static Builder interfaceBuilder(String name);
148
public static Builder enumBuilder(String name);
149
public static Builder annotationBuilder(String name);
150
}
151
152
// Method specification
153
public final class MethodSpec {
154
public static Builder methodBuilder(String name);
155
public static Builder constructorBuilder();
156
}
157
158
// Field specification
159
public final class FieldSpec {
160
public static Builder builder(TypeName type, String name, Modifier... modifiers);
161
}
162
```
163
164
[Code Specifications](./code-specifications.md)
165
166
### Advanced Type System
167
168
Advanced type representations for complex generic scenarios including parameterized types, arrays, type variables, and wildcards.
169
170
```java { .api }
171
// Parameterized types like List<String>
172
public final class ParameterizedTypeName extends TypeName {
173
public static ParameterizedTypeName get(ClassName rawType, TypeName... typeArguments);
174
}
175
176
// Array types like String[]
177
public final class ArrayTypeName extends TypeName {
178
public static ArrayTypeName of(TypeName componentType);
179
}
180
181
// Type variables like T, E, K, V
182
public final class TypeVariableName extends TypeName {
183
public static TypeVariableName get(String name);
184
public static TypeVariableName get(String name, TypeName... bounds);
185
}
186
187
// Wildcard types like ? extends String
188
public final class WildcardTypeName extends TypeName {
189
public static WildcardTypeName subtypeOf(TypeName upperBound);
190
public static WildcardTypeName supertypeOf(TypeName lowerBound);
191
}
192
```
193
194
[Advanced Types](./advanced-types.md)
195
196
### Code Generation
197
198
Template-based code generation system and utilities for generating method bodies, initializers, and managing identifier names.
199
200
```java { .api }
201
// Code block generation with templates
202
public final class CodeBlock {
203
public static CodeBlock of(String format, Object... args);
204
public static Builder builder();
205
206
// Template placeholders:
207
// $L - Literals (direct substitution)
208
// $S - Strings (with proper escaping and quotes)
209
// $T - Types (with automatic import handling)
210
// $N - Names (for referencing other generated elements)
211
}
212
213
// Name allocation utilities
214
public final class NameAllocator implements Cloneable {
215
public String newName(String suggestion);
216
public String newName(String suggestion, Object tag);
217
public String get(Object tag);
218
public static String toJavaIdentifier(String suggestion);
219
}
220
```
221
222
[Code Generation](./code-generation.md)