0
# Code Generation and Printing
1
2
JavaParser provides multiple ways to convert AST nodes back to source code and other formats. The printing system supports pretty-printed Java code, XML representation, and graph visualization formats.
3
4
## Capabilities
5
6
### Pretty Printing
7
8
Convert AST nodes back to formatted Java source code with configurable formatting options.
9
10
```java { .api }
11
/**
12
* Pretty printer for converting AST to formatted Java source code
13
*/
14
public class PrettyPrinter implements ConfigurablePrinter {
15
16
/**
17
* Create pretty printer with default configuration
18
*/
19
public PrettyPrinter();
20
21
/**
22
* Create pretty printer with custom configuration
23
* @param configuration Printer configuration
24
*/
25
public PrettyPrinter(PrettyPrinterConfiguration configuration);
26
27
/**
28
* Print AST node to formatted Java source code
29
* @param node AST node to print
30
* @return Formatted Java source code
31
*/
32
public String print(Node node);
33
}
34
35
/**
36
* Configuration for pretty printer formatting options
37
*/
38
public class PrettyPrinterConfiguration {
39
40
/**
41
* Create default configuration
42
*/
43
public PrettyPrinterConfiguration();
44
45
/**
46
* Set indentation string (default: 4 spaces)
47
* @param indentation String to use for indentation
48
* @return This configuration for chaining
49
*/
50
public PrettyPrinterConfiguration setIndent(String indentation);
51
52
/**
53
* Set line ending style
54
* @param endOfLineCharacter Line ending character(s)
55
* @return This configuration for chaining
56
*/
57
public PrettyPrinterConfiguration setEndOfLineCharacter(String endOfLineCharacter);
58
59
/**
60
* Enable/disable printing of orphan comments
61
* @param printComments true to print comments
62
* @return This configuration for chaining
63
*/
64
public PrettyPrinterConfiguration setPrintComments(boolean printComments);
65
66
/**
67
* Enable/disable printing of Javadoc
68
* @param printJavadoc true to print Javadoc
69
* @return This configuration for chaining
70
*/
71
public PrettyPrinterConfiguration setPrintJavadoc(boolean printJavadoc);
72
73
/**
74
* Set ordering for class members
75
* @param orderByType true to order by member type
76
* @return This configuration for chaining
77
*/
78
public PrettyPrinterConfiguration setOrderByType(boolean orderByType);
79
80
/**
81
* Set column width for formatting
82
* @param columnWidth Maximum column width
83
* @return This configuration for chaining
84
*/
85
public PrettyPrinterConfiguration setColumnWidth(int columnWidth);
86
}
87
```
88
89
**Usage Examples:**
90
91
```java
92
import com.github.javaparser.printer.PrettyPrinter;
93
import com.github.javaparser.printer.PrettyPrinterConfiguration;
94
95
// Basic pretty printing
96
CompilationUnit cu = StaticJavaParser.parse(code);
97
PrettyPrinter printer = new PrettyPrinter();
98
String formattedCode = printer.print(cu);
99
System.out.println(formattedCode);
100
101
// Custom configuration
102
PrettyPrinterConfiguration config = new PrettyPrinterConfiguration()
103
.setIndent("\t") // Use tabs instead of spaces
104
.setEndOfLineCharacter("\n") // Unix line endings
105
.setPrintComments(true)
106
.setColumnWidth(120);
107
108
PrettyPrinter customPrinter = new PrettyPrinter(config);
109
String customFormatted = customPrinter.print(cu);
110
111
// Print specific nodes
112
ClassOrInterfaceDeclaration clazz = cu.findFirst(ClassOrInterfaceDeclaration.class).get();
113
String classCode = printer.print(clazz);
114
115
MethodDeclaration method = cu.findFirst(MethodDeclaration.class).get();
116
String methodCode = printer.print(method);
117
```
118
119
### XML Printing
120
121
Convert AST nodes to XML representation for analysis or processing by other tools.
122
123
```java { .api }
124
/**
125
* XML printer for converting AST to XML format
126
*/
127
public class XmlPrinter {
128
129
/**
130
* Create XML printer with default settings
131
*/
132
public XmlPrinter();
133
134
/**
135
* Create XML printer with indentation enabled/disabled
136
* @param indent true to enable indentation
137
*/
138
public XmlPrinter(boolean indent);
139
140
/**
141
* Print AST node to XML format
142
* @param node AST node to print
143
* @return XML representation of the AST
144
*/
145
public String print(Node node);
146
147
/**
148
* Print AST node to XML with custom indentation
149
* @param node AST node to print
150
* @param indentLevel Starting indentation level
151
* @return XML representation of the AST
152
*/
153
public String print(Node node, int indentLevel);
154
}
155
```
156
157
**Usage Examples:**
158
159
```java
160
import com.github.javaparser.printer.XmlPrinter;
161
162
CompilationUnit cu = StaticJavaParser.parse(code);
163
164
// Basic XML printing
165
XmlPrinter xmlPrinter = new XmlPrinter(true); // with indentation
166
String xml = xmlPrinter.print(cu);
167
System.out.println(xml);
168
169
// Example XML output:
170
// <CompilationUnit>
171
// <types>
172
// <ClassOrInterfaceDeclaration name="Example" isInterface="false">
173
// <members>
174
// <MethodDeclaration name="hello">
175
// <type>
176
// <VoidType/>
177
// </type>
178
// <body>
179
// <BlockStmt>
180
// <!-- method body nodes -->
181
// </BlockStmt>
182
// </body>
183
// </MethodDeclaration>
184
// </members>
185
// </ClassOrInterfaceDeclaration>
186
// </types>
187
// </CompilationUnit>
188
189
// Print specific nodes to XML
190
MethodDeclaration method = cu.findFirst(MethodDeclaration.class).get();
191
String methodXml = xmlPrinter.print(method);
192
```
193
194
### DOT Graph Printing
195
196
Generate Graphviz DOT format for visualizing AST structure as graphs.
197
198
```java { .api }
199
/**
200
* DOT printer for converting AST to Graphviz DOT format
201
*/
202
public class DotPrinter {
203
204
/**
205
* Create DOT printer
206
*/
207
public DotPrinter();
208
209
/**
210
* Print AST node to DOT format for graph visualization
211
* @param node AST node to print
212
* @return DOT format representation
213
*/
214
public String print(Node node);
215
216
/**
217
* Print with custom node output
218
* @param node AST node to print
219
* @param outputNodeType Function to determine node display
220
* @return DOT format representation
221
*/
222
public String print(Node node, Function<Node, String> outputNodeType);
223
}
224
```
225
226
**Usage Examples:**
227
228
```java
229
import com.github.javaparser.printer.DotPrinter;
230
231
CompilationUnit cu = StaticJavaParser.parse(code);
232
233
// Generate DOT graph
234
DotPrinter dotPrinter = new DotPrinter();
235
String dotGraph = dotPrinter.print(cu);
236
237
// Save to file for visualization with Graphviz
238
try (FileWriter writer = new FileWriter("ast.dot")) {
239
writer.write(dotGraph);
240
}
241
242
// Example DOT output:
243
// digraph {
244
// n0 [label="CompilationUnit"];
245
// n1 [label="ClassOrInterfaceDeclaration"];
246
// n2 [label="MethodDeclaration"];
247
// n0 -> n1;
248
// n1 -> n2;
249
// // ... more nodes and relationships
250
// }
251
252
// Convert to image with Graphviz command line:
253
// dot -Tpng ast.dot -o ast.png
254
255
// Custom node labeling
256
String customDot = dotPrinter.print(cu, node -> {
257
if (node instanceof ClassOrInterfaceDeclaration) {
258
return "Class: " + ((ClassOrInterfaceDeclaration) node).getNameAsString();
259
} else if (node instanceof MethodDeclaration) {
260
return "Method: " + ((MethodDeclaration) node).getNameAsString();
261
}
262
return node.getClass().getSimpleName();
263
});
264
```
265
266
### Default Pretty Printing
267
268
Convenient methods for simple pretty printing without configuration.
269
270
```java { .api }
271
/**
272
* Simple toString() method for basic printing
273
*/
274
// All Node classes override toString() to provide basic string representation
275
CompilationUnit cu = StaticJavaParser.parse(code);
276
String basicString = cu.toString(); // Uses default pretty printer
277
278
/**
279
* Static utility methods for printing
280
*/
281
public final class StaticJavaParser {
282
283
/**
284
* Pretty print any node using default settings
285
* @param node Node to print
286
* @return Pretty printed source code
287
*/
288
public static String print(Node node);
289
}
290
```
291
292
**Usage Examples:**
293
294
```java
295
// Simple printing
296
CompilationUnit cu = StaticJavaParser.parse(code);
297
298
// Using toString()
299
String simple = cu.toString();
300
301
// Using static print method
302
String pretty = StaticJavaParser.print(cu);
303
304
// Print individual nodes
305
for (MethodDeclaration method : cu.findAll(MethodDeclaration.class)) {
306
System.out.println("Method: " + method.toString());
307
}
308
```
309
310
### Custom Printing with Visitors
311
312
Create custom printing formats by implementing visitors.
313
314
```java { .api }
315
/**
316
* Example custom printer using visitor pattern
317
*/
318
public class CustomPrinter extends VoidVisitorAdapter<StringBuilder> {
319
320
@Override
321
public void visit(ClassOrInterfaceDeclaration n, StringBuilder sb) {
322
sb.append("Class: ").append(n.getNameAsString()).append("\n");
323
super.visit(n, sb);
324
}
325
326
@Override
327
public void visit(MethodDeclaration n, StringBuilder sb) {
328
sb.append(" Method: ").append(n.getNameAsString());
329
sb.append(" returns ").append(n.getType().toString()).append("\n");
330
super.visit(n, sb);
331
}
332
333
@Override
334
public void visit(FieldDeclaration n, StringBuilder sb) {
335
n.getVariables().forEach(var ->
336
sb.append(" Field: ").append(var.getNameAsString()).append("\n"));
337
super.visit(n, sb);
338
}
339
}
340
```
341
342
**Usage Examples:**
343
344
```java
345
// Use custom printer
346
CompilationUnit cu = StaticJavaParser.parse(code);
347
StringBuilder output = new StringBuilder();
348
cu.accept(new CustomPrinter(), output);
349
System.out.println(output.toString());
350
351
// Example output:
352
// Class: Example
353
// Field: name
354
// Method: getName returns String
355
// Method: setName returns void
356
```
357
358
### Configurable Printer Interface
359
360
All printers implement the common interface for consistent usage.
361
362
```java { .api }
363
/**
364
* Base interface for all printers
365
*/
366
public interface Printer {
367
368
/**
369
* Print node to string representation
370
* @param node Node to print
371
* @return String representation
372
*/
373
String print(Node node);
374
}
375
376
/**
377
* Interface for printers with configuration options
378
*/
379
public interface ConfigurablePrinter extends Printer {
380
381
/**
382
* Get current configuration
383
* @return Current printer configuration
384
*/
385
Object getConfiguration();
386
}
387
```
388
389
### Printing Utilities
390
391
Utility methods for common printing tasks.
392
393
```java { .api }
394
/**
395
* Utility methods for printing and formatting
396
*/
397
public class PrinterUtils {
398
399
/**
400
* Print node with line numbers
401
* @param node Node to print
402
* @return String with line numbers
403
*/
404
public static String printWithLineNumbers(Node node);
405
406
/**
407
* Print only the signature of methods/constructors
408
* @param callable Method or constructor declaration
409
* @return Signature string
410
*/
411
public static String printSignature(CallableDeclaration<?> callable);
412
413
/**
414
* Print node with syntax highlighting markers
415
* @param node Node to print
416
* @return String with highlighting markers
417
*/
418
public static String printWithHighlighting(Node node);
419
}
420
```
421
422
**Usage Examples:**
423
424
```java
425
// Print with line numbers
426
CompilationUnit cu = StaticJavaParser.parse(code);
427
String withLines = PrinterUtils.printWithLineNumbers(cu);
428
429
// Print method signatures only
430
List<MethodDeclaration> methods = cu.findAll(MethodDeclaration.class);
431
for (MethodDeclaration method : methods) {
432
String signature = PrinterUtils.printSignature(method);
433
System.out.println("Signature: " + signature);
434
}
435
```
436
437
## Printer Configuration Options
438
439
```java { .api }
440
// Comprehensive printer configuration
441
PrettyPrinterConfiguration config = new PrettyPrinterConfiguration()
442
.setIndent(" ") // 4 spaces
443
.setEndOfLineCharacter("\n") // Unix line endings
444
.setPrintComments(true) // Include comments
445
.setPrintJavadoc(true) // Include Javadoc
446
.setOrderByType(false) // Preserve declaration order
447
.setColumnWidth(100) // Max line width
448
.setIndentCaseInSwitch(true) // Indent case statements
449
.setIndentSize(4) // Indentation size
450
.setTabWidth(4); // Tab width
451
452
PrettyPrinter printer = new PrettyPrinter(config);
453
```