Master Java Code Analysis with JavaParser: Real‑World Examples
This article introduces JavaParser, an open‑source library for parsing Java source code into an AST, and walks through practical cases covering dependency setup, basic parsing, class and method extraction, code modification, class generation, and comprehensive analysis with code snippets and output screenshots.
1. Introduction
JavaParser is an open‑source library for parsing Java source code into an abstract syntax tree (AST). It supports Java up to version 21 and enables analysis, transformation, and generation of Java code.
2. Practical Cases
2.1 Dependency Management
<code><dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>3.26.3</version>
</dependency>
</code>Download the latest version (3.26.3 supports Java 21).
2.2 Basic Usage
Parse a simple Hello.java file:
<code>FileInputStream in = new FileInputStream(
new File("src/main/java/com/pack/test/Hello.java"));
JavaParser javaParser = new JavaParser();
ParseResult<CompilationUnit> result = javaParser.parse(in);
System.out.println(result.getResult().get());
</code>The resulting CompilationUnit represents the AST of the source file.
2.3 Parse Class Names
<code>FileInputStream in = new FileInputStream(
new File("src/main/java/com/pack/test/Hello.java"));
JavaParser javaParser = new JavaParser();
ParseResult<CompilationUnit> result = javaParser.parse(in);
CompilationUnit cu = result.getResult().get();
cu.findAll(ClassOrInterfaceDeclaration.class).forEach(c ->
System.err.println(c.getName()));
</code>Outputs class names such as Hello . Nested classes are also discovered.
2.4 Parse Methods
<code>cu.findAll(MethodDeclaration.class).forEach(m ->
System.err.println(m.getName()));
</code>Prints method names like fn and main . The MethodDeclaration node covers all methods regardless of modifiers.
2.5 Add / Delete Methods
<code>// Add a public method named say
cu.getClassByName("Hello").ifPresent(c -> {
MethodDeclaration method = c.addMethod("say", Modifier.Keyword.PUBLIC);
BlockStmt body = new JavaParser().parseBlock("{System.out.println(\"Hello\");}")
.getResult().get();
method.setBody(body);
});
System.err.println(cu.toString());
// Delete method fn
cu.findAll(MethodDeclaration.class).stream()
.filter(m -> m.getNameAsString().equals("fn"))
.forEach(MethodDeclaration::remove);
System.err.println(cu.toString());
</code>The source before and after modification is shown in the screenshots.
2.6 Generate Classes
<code>CompilationUnit cu = new CompilationUnit();
ClassOrInterfaceDeclaration classDecl = cu.addClass("DynamicGenClass");
MethodDeclaration method = classDecl.addMethod("genMethod", Modifier.Keyword.PUBLIC);
JavaParser parser = new JavaParser();
BlockStmt body = parser.parseBlock("{ System.out.println(\"I am a dynamically generated method.\"); }")
.getResult().get();
method.setBody(body);
System.out.println(cu.toString());
</code>Outputs a newly generated class with a method.
2.7 Comprehensive Code Analysis
Analyzes method length and replaces magic numbers in a sample Example.java file.
<code>public class JavaParserTest07 {
private static final int MAX_METHOD_LENGTH = 5;
public static void main(String[] args) throws IOException {
Path path = Paths.get("src/main/java/com/pack/test/Example.java");
String code = Files.readString(path);
CompilationUnit cu = StaticJavaParser.parse(code);
cu.accept(new MethodLengthChecker(), null);
MagicNumberDetector detector = new MagicNumberDetector();
cu.accept(detector, null);
replaceMagicNumbers(cu, detector.getMagicNumbers());
System.out.println(cu);
}
// Visitor classes omitted for brevity
}
</code>The tool reports long methods, detects magic numbers, replaces them with named constants, and adds corresponding fields.
All examples demonstrate how JavaParser can be used for parsing, inspecting, modifying, and generating Java source code.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.