A comprehensive Java parsing library providing complete support for parsing Java source code from Java 1.0 through Java 21 with advanced analysis functionalities.
—
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.
Convert AST nodes back to formatted Java source code with configurable formatting options.
/**
* Pretty printer for converting AST to formatted Java source code
*/
public class PrettyPrinter implements ConfigurablePrinter {
/**
* Create pretty printer with default configuration
*/
public PrettyPrinter();
/**
* Create pretty printer with custom configuration
* @param configuration Printer configuration
*/
public PrettyPrinter(PrettyPrinterConfiguration configuration);
/**
* Print AST node to formatted Java source code
* @param node AST node to print
* @return Formatted Java source code
*/
public String print(Node node);
}
/**
* Configuration for pretty printer formatting options
*/
public class PrettyPrinterConfiguration {
/**
* Create default configuration
*/
public PrettyPrinterConfiguration();
/**
* Set indentation string (default: 4 spaces)
* @param indentation String to use for indentation
* @return This configuration for chaining
*/
public PrettyPrinterConfiguration setIndent(String indentation);
/**
* Set line ending style
* @param endOfLineCharacter Line ending character(s)
* @return This configuration for chaining
*/
public PrettyPrinterConfiguration setEndOfLineCharacter(String endOfLineCharacter);
/**
* Enable/disable printing of orphan comments
* @param printComments true to print comments
* @return This configuration for chaining
*/
public PrettyPrinterConfiguration setPrintComments(boolean printComments);
/**
* Enable/disable printing of Javadoc
* @param printJavadoc true to print Javadoc
* @return This configuration for chaining
*/
public PrettyPrinterConfiguration setPrintJavadoc(boolean printJavadoc);
/**
* Set ordering for class members
* @param orderByType true to order by member type
* @return This configuration for chaining
*/
public PrettyPrinterConfiguration setOrderByType(boolean orderByType);
/**
* Set column width for formatting
* @param columnWidth Maximum column width
* @return This configuration for chaining
*/
public PrettyPrinterConfiguration setColumnWidth(int columnWidth);
}Usage Examples:
import com.github.javaparser.printer.PrettyPrinter;
import com.github.javaparser.printer.PrettyPrinterConfiguration;
// Basic pretty printing
CompilationUnit cu = StaticJavaParser.parse(code);
PrettyPrinter printer = new PrettyPrinter();
String formattedCode = printer.print(cu);
System.out.println(formattedCode);
// Custom configuration
PrettyPrinterConfiguration config = new PrettyPrinterConfiguration()
.setIndent("\t") // Use tabs instead of spaces
.setEndOfLineCharacter("\n") // Unix line endings
.setPrintComments(true)
.setColumnWidth(120);
PrettyPrinter customPrinter = new PrettyPrinter(config);
String customFormatted = customPrinter.print(cu);
// Print specific nodes
ClassOrInterfaceDeclaration clazz = cu.findFirst(ClassOrInterfaceDeclaration.class).get();
String classCode = printer.print(clazz);
MethodDeclaration method = cu.findFirst(MethodDeclaration.class).get();
String methodCode = printer.print(method);Convert AST nodes to XML representation for analysis or processing by other tools.
/**
* XML printer for converting AST to XML format
*/
public class XmlPrinter {
/**
* Create XML printer with default settings
*/
public XmlPrinter();
/**
* Create XML printer with indentation enabled/disabled
* @param indent true to enable indentation
*/
public XmlPrinter(boolean indent);
/**
* Print AST node to XML format
* @param node AST node to print
* @return XML representation of the AST
*/
public String print(Node node);
/**
* Print AST node to XML with custom indentation
* @param node AST node to print
* @param indentLevel Starting indentation level
* @return XML representation of the AST
*/
public String print(Node node, int indentLevel);
}Usage Examples:
import com.github.javaparser.printer.XmlPrinter;
CompilationUnit cu = StaticJavaParser.parse(code);
// Basic XML printing
XmlPrinter xmlPrinter = new XmlPrinter(true); // with indentation
String xml = xmlPrinter.print(cu);
System.out.println(xml);
// Example XML output:
// <CompilationUnit>
// <types>
// <ClassOrInterfaceDeclaration name="Example" isInterface="false">
// <members>
// <MethodDeclaration name="hello">
// <type>
// <VoidType/>
// </type>
// <body>
// <BlockStmt>
// <!-- method body nodes -->
// </BlockStmt>
// </body>
// </MethodDeclaration>
// </members>
// </ClassOrInterfaceDeclaration>
// </types>
// </CompilationUnit>
// Print specific nodes to XML
MethodDeclaration method = cu.findFirst(MethodDeclaration.class).get();
String methodXml = xmlPrinter.print(method);Generate Graphviz DOT format for visualizing AST structure as graphs.
/**
* DOT printer for converting AST to Graphviz DOT format
*/
public class DotPrinter {
/**
* Create DOT printer
*/
public DotPrinter();
/**
* Print AST node to DOT format for graph visualization
* @param node AST node to print
* @return DOT format representation
*/
public String print(Node node);
/**
* Print with custom node output
* @param node AST node to print
* @param outputNodeType Function to determine node display
* @return DOT format representation
*/
public String print(Node node, Function<Node, String> outputNodeType);
}Usage Examples:
import com.github.javaparser.printer.DotPrinter;
CompilationUnit cu = StaticJavaParser.parse(code);
// Generate DOT graph
DotPrinter dotPrinter = new DotPrinter();
String dotGraph = dotPrinter.print(cu);
// Save to file for visualization with Graphviz
try (FileWriter writer = new FileWriter("ast.dot")) {
writer.write(dotGraph);
}
// Example DOT output:
// digraph {
// n0 [label="CompilationUnit"];
// n1 [label="ClassOrInterfaceDeclaration"];
// n2 [label="MethodDeclaration"];
// n0 -> n1;
// n1 -> n2;
// // ... more nodes and relationships
// }
// Convert to image with Graphviz command line:
// dot -Tpng ast.dot -o ast.png
// Custom node labeling
String customDot = dotPrinter.print(cu, node -> {
if (node instanceof ClassOrInterfaceDeclaration) {
return "Class: " + ((ClassOrInterfaceDeclaration) node).getNameAsString();
} else if (node instanceof MethodDeclaration) {
return "Method: " + ((MethodDeclaration) node).getNameAsString();
}
return node.getClass().getSimpleName();
});Convenient methods for simple pretty printing without configuration.
/**
* Simple toString() method for basic printing
*/
// All Node classes override toString() to provide basic string representation
CompilationUnit cu = StaticJavaParser.parse(code);
String basicString = cu.toString(); // Uses default pretty printer
/**
* Static utility methods for printing
*/
public final class StaticJavaParser {
/**
* Pretty print any node using default settings
* @param node Node to print
* @return Pretty printed source code
*/
public static String print(Node node);
}Usage Examples:
// Simple printing
CompilationUnit cu = StaticJavaParser.parse(code);
// Using toString()
String simple = cu.toString();
// Using static print method
String pretty = StaticJavaParser.print(cu);
// Print individual nodes
for (MethodDeclaration method : cu.findAll(MethodDeclaration.class)) {
System.out.println("Method: " + method.toString());
}Create custom printing formats by implementing visitors.
/**
* Example custom printer using visitor pattern
*/
public class CustomPrinter extends VoidVisitorAdapter<StringBuilder> {
@Override
public void visit(ClassOrInterfaceDeclaration n, StringBuilder sb) {
sb.append("Class: ").append(n.getNameAsString()).append("\n");
super.visit(n, sb);
}
@Override
public void visit(MethodDeclaration n, StringBuilder sb) {
sb.append(" Method: ").append(n.getNameAsString());
sb.append(" returns ").append(n.getType().toString()).append("\n");
super.visit(n, sb);
}
@Override
public void visit(FieldDeclaration n, StringBuilder sb) {
n.getVariables().forEach(var ->
sb.append(" Field: ").append(var.getNameAsString()).append("\n"));
super.visit(n, sb);
}
}Usage Examples:
// Use custom printer
CompilationUnit cu = StaticJavaParser.parse(code);
StringBuilder output = new StringBuilder();
cu.accept(new CustomPrinter(), output);
System.out.println(output.toString());
// Example output:
// Class: Example
// Field: name
// Method: getName returns String
// Method: setName returns voidAll printers implement the common interface for consistent usage.
/**
* Base interface for all printers
*/
public interface Printer {
/**
* Print node to string representation
* @param node Node to print
* @return String representation
*/
String print(Node node);
}
/**
* Interface for printers with configuration options
*/
public interface ConfigurablePrinter extends Printer {
/**
* Get current configuration
* @return Current printer configuration
*/
Object getConfiguration();
}Utility methods for common printing tasks.
/**
* Utility methods for printing and formatting
*/
public class PrinterUtils {
/**
* Print node with line numbers
* @param node Node to print
* @return String with line numbers
*/
public static String printWithLineNumbers(Node node);
/**
* Print only the signature of methods/constructors
* @param callable Method or constructor declaration
* @return Signature string
*/
public static String printSignature(CallableDeclaration<?> callable);
/**
* Print node with syntax highlighting markers
* @param node Node to print
* @return String with highlighting markers
*/
public static String printWithHighlighting(Node node);
}Usage Examples:
// Print with line numbers
CompilationUnit cu = StaticJavaParser.parse(code);
String withLines = PrinterUtils.printWithLineNumbers(cu);
// Print method signatures only
List<MethodDeclaration> methods = cu.findAll(MethodDeclaration.class);
for (MethodDeclaration method : methods) {
String signature = PrinterUtils.printSignature(method);
System.out.println("Signature: " + signature);
}// Comprehensive printer configuration
PrettyPrinterConfiguration config = new PrettyPrinterConfiguration()
.setIndent(" ") // 4 spaces
.setEndOfLineCharacter("\n") // Unix line endings
.setPrintComments(true) // Include comments
.setPrintJavadoc(true) // Include Javadoc
.setOrderByType(false) // Preserve declaration order
.setColumnWidth(100) // Max line width
.setIndentCaseInSwitch(true) // Indent case statements
.setIndentSize(4) // Indentation size
.setTabWidth(4); // Tab width
PrettyPrinter printer = new PrettyPrinter(config);Install with Tessl CLI
npx tessl i tessl/maven-com-github-javaparser--javaparser-core