SlideShare a Scribd company logo
JavaParser
A tool to generate, analyze, and refactor Java code
Federico Tomassetti founder of
Goal
JavaParser is evolving in a suite of libraries to support:
• Code generation
• Code analysis
• Code refactoring
It has a growing user-base but we are not sure on which usages
to focus:
Can you help us figure out
who could we serve better?
What JavaParser does?
JavaParser… parse Java code into a Java AST
package foo.bar;
class A {
int field;
}
CompilationUnit
PackageDecl ClassDecl
FieldDecl
PrimitiveType
What JavaParser does?
JavaParser unparse an AST into code
package foo.bar;
class A {
int field;
}
CompilationUnit
PackageDecl ClassDecl
FieldDecl
PrimitiveType
Why do you need symbol resolving?
int foo;
public void aMethod(int foo) {
foo = 1;
}
public void anotherMethod() {
foo = 1;
}
To JP these two statements looks the same: they produce the same
AST nodes.
It is the assignment of a thing named ”foo”, no idea what that thing is
public void print1(String foo) {
System.out.print(foo);
}
public void print2(int foo) {
System.out.print(foo);
}
To JP these two statements looks the same: they produce the same
AST nodes.
It is the call of a method named “print”, no idea which signature that
has
Why do you need symbol resolving?
class A { }
public void creator1() {
new A();
}
public void creator2() {
class A { }
new A();
}
To JP these two statements looks the same: they produce the same
AST nodes.
It is the instantiation of a class named “A”, no idea where it is defined
Why do you need symbol resolving?
What JavaSymbolSolver does?
JavaSymbolSolver resolves symbols in the JavaParser AST
package foo.bar;
class C {
D field;
}
package foo.bar;
class D {
}
CompilationUnit
PackageDecl ClassDecl
FieldDecl
ReferenceType
Relationship JP & JSS
Certain methods in the AST requires additional intelligence.
myCallExpression.calculateResolvedType();
myCallExpression.getName();
JSS not enabled JSS enabled
JSS not enabled JSS enabled
Configuring JavaSymbolSolver
A typical usage:
CombinedTypeSolver typeSolver = new CombinedTypeSolver(
new ReflectionTypeSolver(),
new JavaParserTypeSolver(new File("src/main/java")),
new JavaParserTypeSolver(new File("src/test/java")),
new JarTypeSolver("libs/guava.jar"),
new JarTypeSolver("libs/log4j.jar"));
Supporting code generation
We want to support people who has to generate code:
• Because they want to generate boilerplate code from
some source (e.g., a database schema)
• They want to build a transpiler targeting Java
JavaParser to generate code
CompilationUnit cu = new CompilationUnit();
cu.setPackageDeclaration("jpexample.model");
ClassOrInterfaceDeclaration book =
cu.addClass("Book");
book.addField("String", "title");
book.addField("Person", "author");
JavaParser to generate code
book.addConstructor(Modifier.PUBLIC)
.addParameter("String", "title")
.addParameter("Person", "author")
.setBody(new BlockStmt()
.addStatement(new ExpressionStmt(new AssignExpr(
new FieldAccessExpr(
new ThisExpr(), "title"),
new NameExpr("title"),
AssignExpr.Operator.ASSIGN)))
.addStatement(new ExpressionStmt(new AssignExpr(
new FieldAccessExpr(
new ThisExpr(), "author"),
new NameExpr("author"),
AssignExpr.Operator.ASSIGN))));
JavaParser to generate code
book.addMethod("getTitle", Modifier.PUBLIC).setBody(
new BlockStmt().addStatement(
new ReturnStmt(new NameExpr("title"))));
book.addMethod("getAuthor", Modifier.PUBLIC).setBody(
new BlockStmt().addStatement(
new ReturnStmt(new NameExpr("author"))));
System.out.println(cu.toString());
JavaParser to generate code
package jpexample.model;
public class Book {
String title;
Person author;
public Book(String title, Person author) {
this.title = title;
this.author = author;
}
public void getTitle() {
return title;
}
public void getAuthor() {
return author;
}
}
Supporting code analysis
We want to support people who have to analyse code:
• Because they want some metrics on code
• Because they want to ensure some quality standards are
met
• Because they want to write quick, one-off queries about
their codebase
JavaParser to run queries
Question: How many methods take more than 3 parameters?
long n = getNodes(allCus, MethodDeclaration.class)
.stream()
.filter(m -> m.getParameters().size() > 3)
.count();
System.out.println("N of methods with >3 params: "
+ n);
Answer: 11
JavaParser to run queries
Question: What are the three top classes with most methods?
Answer: CoreMatchers: 35 methods
BaseDescription: 13 methods
IsEqual: 9 methods
getNodes(allCus, ClassOrInterfaceDeclaration.class)
.stream()
.filter(c -> !c.isInterface())
.sorted(Comparator.comparingInt(o ->
-1 * o.getMethods().size()))
.limit(3)
.forEach(c ->
System.out.println(c.getNameAsString()
+ ": " + c.getMethods().size()
+ " methods"));
JavaParser to run queries
Question: What is the class with most ancestors?
Answer: org.hamcrest.core.StringContains: org.hamcrest.core.SubstringMatcher,
org.hamcrest.TypeSafeMatcher, org.hamcrest.BaseMatcher, org.hamcrest.Matcher,
org.hamcrest.SelfDescribing, java.lang.Object
ResolvedReferenceTypeDeclaration c = getNodes(allCus,
ClassOrInterfaceDeclaration.class)
.stream()
.filter(c -> !c.isInterface())
.map(c -> c.resolve())
.sorted(Comparator.comparingInt(o ->
-1 * o.getAllAncestors().size()))
.findFirst().get();
List<String> ancestorNames = c.getAllAncestors()
.stream()
.map(a -> a.getQualifiedName())
.collect(Collectors.toList());
System.out.println(c.getQualifiedName() + ": " +
String.join(", ", ancestorNames));
JSS at work here
Supporting code refactoring
We want to support people who has to refactor code:
• Because they have to modernize legacy code
• Because they want to update some dependencies and
the API of the libraries used changed
• Because they want to change some usage patterns
JavaParser for automated
refactoring
getNodes(allCus, MethodCallExpr.class)
.stream()
.filter(m -> m.resolveInvokedMethod()
.getQualifiedSignature()
.equals("foo.MyClass.oldMethod(java.lang.String,
int)"))
.forEach(m -> m.replace(replaceCallsToOldMethod(m)));
A new version of a library comes up and a deprecated method named
oldMethod is replaced by newMethod.
The new method takes 3 parameters: the first one as oldMethod but
inverted and the third one is a boolean, which we want to be always
true
JavaParser for automated
refactoring
public MethodCallExpr replaceCallsToOldMethod(
MethodCallExpr methodCall) {
MethodCallExpr newMethodCall = new MethodCallExpr(
methodCall.getScope().get(), "newMethod");
newMethodCall.addArgument(methodCall.getArgument(1));
newMethodCall.addArgument(methodCall.getArgument(0));
newMethodCall.addArgument(new BooleanLiteralExpr(true));
return newMethodCall;
}
Some other features
Comments attribution
void foo() {
// comment1
int a =
1 + 2; // comment2
}
// comment1
int a =
1 + 2;
CompilationUnit cu = JavaParser.parse(code);
ExpressionStmt expressionStmt =
cu.findFirst(ExpressionStmt.class).get() ;
System.out.println("Comment on the expression statement: "
+ expressionStmt.getComment().get().getContent());
Lexical preservation
Pretty printing is good for new code but for existing code users
want lexical preservation.
It is tricky because you need to know how to modify code
preserving the style and making the code correct.
Original code Change Final code
int a, b, c; remove b, adapt commas int a, c;
void foo() {
int a;
}
add new statement, indent
it as statement a previous
line
void foo() {
int a;
a = 0;
}
Things we are considering
JavaParser to identify patterns
We are working on the Matcher library to reduce the complexity, it is in the early
stages
This gives you a list of pairs name-type for all the properties in your bean.
Java templates
We are discussing the idea of Java templates.
We would like to have Java code with placeholders for variable parts
and be able to validate those templates.
class A extends ${BASE_CLASS:Id} {
private ${FIELD_TYPE:Type} myField;
}
class A extends ${BASE_CLASS:Id} {
${E:Expression} myField;
}
OK
KO
Making Java extensible
Researchers (but also a certain company…) would be interested in
writing extensions for Java based on JavaParser.
How can you add a new statement or expression to Java today? You
have to fork the parser. We have one user who forked JavaParser just
to change the grammar file.
We are looking for a better way.
Any suggestions?
JavaParser: Visited
Book on JavaParser and JavaSymbolSolver,
from the core committers.
Avalaible for 0+ $
Currently 1.000+ readers
https://leanpub.com/javaparservisited
Federico Tomassetti
See you on GitHub at
javaparser/javaparser

More Related Content

PDF
Tài liệu data warehouse vietsub
PDF
Phương pháp phát triển phần mềm: Truyền thống và Agile
DOC
Đề tài: Kế toán nguyên vật liệu tại Công ty Lam Sơn Sao Vàng, 9đ - Gửi miễn p...
PPTX
Cloud computing
PDF
Luận văn: Truyền hình băng thông rộng trong mạng HFC, HAY
PDF
Đề tài: Hệ thống giám sát mạng dựa trên phần mềm nguồn mở, HAY
PDF
static libraries and dynamic libraries
PDF
Đề tài: Xây dựng website giới thiệu cho sản phẩm phần mềm, 9đ
Tài liệu data warehouse vietsub
Phương pháp phát triển phần mềm: Truyền thống và Agile
Đề tài: Kế toán nguyên vật liệu tại Công ty Lam Sơn Sao Vàng, 9đ - Gửi miễn p...
Cloud computing
Luận văn: Truyền hình băng thông rộng trong mạng HFC, HAY
Đề tài: Hệ thống giám sát mạng dựa trên phần mềm nguồn mở, HAY
static libraries and dynamic libraries
Đề tài: Xây dựng website giới thiệu cho sản phẩm phần mềm, 9đ

What's hot (20)

DOC
Bài Giảng GIS ICTU
PDF
Tự học sử dụng Linux
PDF
Đồ án Xây dựng bộ mã hóa và giải mã dữ liệu dựa trên thuật toán AES trên nền ...
PDF
Đề cương xử lý ảnh
DOC
Luận văn Thạc sĩ Nghiên cứu triển khai giải pháp đảm bảo an ninh mạng trên nề...
PDF
Báo cáo quản lý cửa hàng máy tính
PDF
Nâng cao năng lực cạnh tranh của FPT
PDF
20210217_sitTokyo_SAP CAI でユーザに優しくしたい
PDF
Đề tài: Kỹ thuật giấu tin thuận nghịch tránh vượt ngưỡng trong ảnh
PDF
Tìm hiểu về điện toán đám mây
PDF
melissa a construcao do amor por uma marca - TCC de Rachel Martins
DOCX
Tìm hiểu và triển khai MySQL Server trên Linux server
PDF
Báo Cáo Đồ Án Tìm Hiểu Công Nghệ NFC
DOCX
PDF
"Making OpenCV Code Run Fast," a Presentation from Intel
PDF
Bài giảng-mạng-viễn-thông-2016
DOC
luan van thac si su dung phan mem nagios giam sat he thong mang
DOC
Tìm hiều về mạng riêng ảo VPN-Virtual Private Network
PDF
Download IObit Driver Booster Pro Crack Latest Version [Updated]
Bài Giảng GIS ICTU
Tự học sử dụng Linux
Đồ án Xây dựng bộ mã hóa và giải mã dữ liệu dựa trên thuật toán AES trên nền ...
Đề cương xử lý ảnh
Luận văn Thạc sĩ Nghiên cứu triển khai giải pháp đảm bảo an ninh mạng trên nề...
Báo cáo quản lý cửa hàng máy tính
Nâng cao năng lực cạnh tranh của FPT
20210217_sitTokyo_SAP CAI でユーザに優しくしたい
Đề tài: Kỹ thuật giấu tin thuận nghịch tránh vượt ngưỡng trong ảnh
Tìm hiểu về điện toán đám mây
melissa a construcao do amor por uma marca - TCC de Rachel Martins
Tìm hiểu và triển khai MySQL Server trên Linux server
Báo Cáo Đồ Án Tìm Hiểu Công Nghệ NFC
"Making OpenCV Code Run Fast," a Presentation from Intel
Bài giảng-mạng-viễn-thông-2016
luan van thac si su dung phan mem nagios giam sat he thong mang
Tìm hiều về mạng riêng ảo VPN-Virtual Private Network
Download IObit Driver Booster Pro Crack Latest Version [Updated]
Ad

Similar to JavaParser - A tool to generate, analyze and refactor Java code (20)

PPT
Slides
PDF
Patterns for JVM languages JokerConf
PPTX
JavaZone 2014 - goto java;
PDF
Lab practical slide show pdf . deeply amazing
PDF
Clojure for Java developers - Stockholm
PPT
Core java by a introduction sandesh sharma
PPTX
Object Oriented Programming - Java
PPT
Learning Java 1 – Introduction
PDF
Java Full Throttle
PPTX
Java n-plus-1-incl-demo-slides
PPT
java training faridabad
PPTX
Modern_Java_Workshop manjunath np hj slave
PPT
Eclipse Day India 2011 - Extending JDT
PDF
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
PDF
JCConf 2022 - New Features in Java 18 & 19
PPTX
Core Java Tutorials by Mahika Tutorials
PDF
Java, what's next?
PDF
Advanced Debugging Using Java Bytecodes
PPTX
Core-Java-by-Mahika-Tutor.9459891.powerpoint.pptx
PPTX
Mastering Java Bytecode - JAX.de 2012
Slides
Patterns for JVM languages JokerConf
JavaZone 2014 - goto java;
Lab practical slide show pdf . deeply amazing
Clojure for Java developers - Stockholm
Core java by a introduction sandesh sharma
Object Oriented Programming - Java
Learning Java 1 – Introduction
Java Full Throttle
Java n-plus-1-incl-demo-slides
java training faridabad
Modern_Java_Workshop manjunath np hj slave
Eclipse Day India 2011 - Extending JDT
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
JCConf 2022 - New Features in Java 18 & 19
Core Java Tutorials by Mahika Tutorials
Java, what's next?
Advanced Debugging Using Java Bytecodes
Core-Java-by-Mahika-Tutor.9459891.powerpoint.pptx
Mastering Java Bytecode - JAX.de 2012
Ad

More from Federico Tomassetti (12)

PDF
Jariko - A JVM interpreter for RPG written in kotlin
PDF
How do you create a programming language for the JVM?
PDF
Building languages with Kotlin
ODP
Building languages with Kotlin
PDF
Automatically Spotting Cross-language Relations
PPTX
Lifting variability from C to mbeddr-C
PDF
Maturity of Software Modelling and Model Driven Engineering: a Survey in the ...
PDF
Eclipse Florence Day: Modeling in the Italian Industry
PPTX
Estendere Java con il Meta Programming System di JetBrains
PDF
What is Federico doing?
PDF
Xtext Un Framework Per La Creazione Di Dsl
PDF
Model Driven Web Development Solutions
Jariko - A JVM interpreter for RPG written in kotlin
How do you create a programming language for the JVM?
Building languages with Kotlin
Building languages with Kotlin
Automatically Spotting Cross-language Relations
Lifting variability from C to mbeddr-C
Maturity of Software Modelling and Model Driven Engineering: a Survey in the ...
Eclipse Florence Day: Modeling in the Italian Industry
Estendere Java con il Meta Programming System di JetBrains
What is Federico doing?
Xtext Un Framework Per La Creazione Di Dsl
Model Driven Web Development Solutions

Recently uploaded (20)

PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Digital Strategies for Manufacturing Companies
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
System and Network Administraation Chapter 3
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
System and Network Administration Chapter 2
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
Introduction to Artificial Intelligence
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
How to Migrate SBCGlobal Email to Yahoo Easily
PTS Company Brochure 2025 (1).pdf.......
Digital Strategies for Manufacturing Companies
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
System and Network Administraation Chapter 3
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Navsoft: AI-Powered Business Solutions & Custom Software Development
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
System and Network Administration Chapter 2
Odoo POS Development Services by CandidRoot Solutions
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
L1 - Introduction to python Backend.pptx
Reimagine Home Health with the Power of Agentic AI​
Introduction to Artificial Intelligence
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
CHAPTER 2 - PM Management and IT Context
VVF-Customer-Presentation2025-Ver1.9.pptx

JavaParser - A tool to generate, analyze and refactor Java code

  • 1. JavaParser A tool to generate, analyze, and refactor Java code Federico Tomassetti founder of
  • 2. Goal JavaParser is evolving in a suite of libraries to support: • Code generation • Code analysis • Code refactoring It has a growing user-base but we are not sure on which usages to focus: Can you help us figure out who could we serve better?
  • 3. What JavaParser does? JavaParser… parse Java code into a Java AST package foo.bar; class A { int field; } CompilationUnit PackageDecl ClassDecl FieldDecl PrimitiveType
  • 4. What JavaParser does? JavaParser unparse an AST into code package foo.bar; class A { int field; } CompilationUnit PackageDecl ClassDecl FieldDecl PrimitiveType
  • 5. Why do you need symbol resolving? int foo; public void aMethod(int foo) { foo = 1; } public void anotherMethod() { foo = 1; } To JP these two statements looks the same: they produce the same AST nodes. It is the assignment of a thing named ”foo”, no idea what that thing is
  • 6. public void print1(String foo) { System.out.print(foo); } public void print2(int foo) { System.out.print(foo); } To JP these two statements looks the same: they produce the same AST nodes. It is the call of a method named “print”, no idea which signature that has Why do you need symbol resolving?
  • 7. class A { } public void creator1() { new A(); } public void creator2() { class A { } new A(); } To JP these two statements looks the same: they produce the same AST nodes. It is the instantiation of a class named “A”, no idea where it is defined Why do you need symbol resolving?
  • 8. What JavaSymbolSolver does? JavaSymbolSolver resolves symbols in the JavaParser AST package foo.bar; class C { D field; } package foo.bar; class D { } CompilationUnit PackageDecl ClassDecl FieldDecl ReferenceType
  • 9. Relationship JP & JSS Certain methods in the AST requires additional intelligence. myCallExpression.calculateResolvedType(); myCallExpression.getName(); JSS not enabled JSS enabled JSS not enabled JSS enabled
  • 10. Configuring JavaSymbolSolver A typical usage: CombinedTypeSolver typeSolver = new CombinedTypeSolver( new ReflectionTypeSolver(), new JavaParserTypeSolver(new File("src/main/java")), new JavaParserTypeSolver(new File("src/test/java")), new JarTypeSolver("libs/guava.jar"), new JarTypeSolver("libs/log4j.jar"));
  • 11. Supporting code generation We want to support people who has to generate code: • Because they want to generate boilerplate code from some source (e.g., a database schema) • They want to build a transpiler targeting Java
  • 12. JavaParser to generate code CompilationUnit cu = new CompilationUnit(); cu.setPackageDeclaration("jpexample.model"); ClassOrInterfaceDeclaration book = cu.addClass("Book"); book.addField("String", "title"); book.addField("Person", "author");
  • 13. JavaParser to generate code book.addConstructor(Modifier.PUBLIC) .addParameter("String", "title") .addParameter("Person", "author") .setBody(new BlockStmt() .addStatement(new ExpressionStmt(new AssignExpr( new FieldAccessExpr( new ThisExpr(), "title"), new NameExpr("title"), AssignExpr.Operator.ASSIGN))) .addStatement(new ExpressionStmt(new AssignExpr( new FieldAccessExpr( new ThisExpr(), "author"), new NameExpr("author"), AssignExpr.Operator.ASSIGN))));
  • 14. JavaParser to generate code book.addMethod("getTitle", Modifier.PUBLIC).setBody( new BlockStmt().addStatement( new ReturnStmt(new NameExpr("title")))); book.addMethod("getAuthor", Modifier.PUBLIC).setBody( new BlockStmt().addStatement( new ReturnStmt(new NameExpr("author")))); System.out.println(cu.toString());
  • 15. JavaParser to generate code package jpexample.model; public class Book { String title; Person author; public Book(String title, Person author) { this.title = title; this.author = author; } public void getTitle() { return title; } public void getAuthor() { return author; } }
  • 16. Supporting code analysis We want to support people who have to analyse code: • Because they want some metrics on code • Because they want to ensure some quality standards are met • Because they want to write quick, one-off queries about their codebase
  • 17. JavaParser to run queries Question: How many methods take more than 3 parameters? long n = getNodes(allCus, MethodDeclaration.class) .stream() .filter(m -> m.getParameters().size() > 3) .count(); System.out.println("N of methods with >3 params: " + n); Answer: 11
  • 18. JavaParser to run queries Question: What are the three top classes with most methods? Answer: CoreMatchers: 35 methods BaseDescription: 13 methods IsEqual: 9 methods getNodes(allCus, ClassOrInterfaceDeclaration.class) .stream() .filter(c -> !c.isInterface()) .sorted(Comparator.comparingInt(o -> -1 * o.getMethods().size())) .limit(3) .forEach(c -> System.out.println(c.getNameAsString() + ": " + c.getMethods().size() + " methods"));
  • 19. JavaParser to run queries Question: What is the class with most ancestors? Answer: org.hamcrest.core.StringContains: org.hamcrest.core.SubstringMatcher, org.hamcrest.TypeSafeMatcher, org.hamcrest.BaseMatcher, org.hamcrest.Matcher, org.hamcrest.SelfDescribing, java.lang.Object ResolvedReferenceTypeDeclaration c = getNodes(allCus, ClassOrInterfaceDeclaration.class) .stream() .filter(c -> !c.isInterface()) .map(c -> c.resolve()) .sorted(Comparator.comparingInt(o -> -1 * o.getAllAncestors().size())) .findFirst().get(); List<String> ancestorNames = c.getAllAncestors() .stream() .map(a -> a.getQualifiedName()) .collect(Collectors.toList()); System.out.println(c.getQualifiedName() + ": " + String.join(", ", ancestorNames)); JSS at work here
  • 20. Supporting code refactoring We want to support people who has to refactor code: • Because they have to modernize legacy code • Because they want to update some dependencies and the API of the libraries used changed • Because they want to change some usage patterns
  • 21. JavaParser for automated refactoring getNodes(allCus, MethodCallExpr.class) .stream() .filter(m -> m.resolveInvokedMethod() .getQualifiedSignature() .equals("foo.MyClass.oldMethod(java.lang.String, int)")) .forEach(m -> m.replace(replaceCallsToOldMethod(m))); A new version of a library comes up and a deprecated method named oldMethod is replaced by newMethod. The new method takes 3 parameters: the first one as oldMethod but inverted and the third one is a boolean, which we want to be always true
  • 22. JavaParser for automated refactoring public MethodCallExpr replaceCallsToOldMethod( MethodCallExpr methodCall) { MethodCallExpr newMethodCall = new MethodCallExpr( methodCall.getScope().get(), "newMethod"); newMethodCall.addArgument(methodCall.getArgument(1)); newMethodCall.addArgument(methodCall.getArgument(0)); newMethodCall.addArgument(new BooleanLiteralExpr(true)); return newMethodCall; }
  • 24. Comments attribution void foo() { // comment1 int a = 1 + 2; // comment2 } // comment1 int a = 1 + 2; CompilationUnit cu = JavaParser.parse(code); ExpressionStmt expressionStmt = cu.findFirst(ExpressionStmt.class).get() ; System.out.println("Comment on the expression statement: " + expressionStmt.getComment().get().getContent());
  • 25. Lexical preservation Pretty printing is good for new code but for existing code users want lexical preservation. It is tricky because you need to know how to modify code preserving the style and making the code correct. Original code Change Final code int a, b, c; remove b, adapt commas int a, c; void foo() { int a; } add new statement, indent it as statement a previous line void foo() { int a; a = 0; }
  • 26. Things we are considering
  • 27. JavaParser to identify patterns We are working on the Matcher library to reduce the complexity, it is in the early stages This gives you a list of pairs name-type for all the properties in your bean.
  • 28. Java templates We are discussing the idea of Java templates. We would like to have Java code with placeholders for variable parts and be able to validate those templates. class A extends ${BASE_CLASS:Id} { private ${FIELD_TYPE:Type} myField; } class A extends ${BASE_CLASS:Id} { ${E:Expression} myField; } OK KO
  • 29. Making Java extensible Researchers (but also a certain company…) would be interested in writing extensions for Java based on JavaParser. How can you add a new statement or expression to Java today? You have to fork the parser. We have one user who forked JavaParser just to change the grammar file. We are looking for a better way. Any suggestions?
  • 30. JavaParser: Visited Book on JavaParser and JavaSymbolSolver, from the core committers. Avalaible for 0+ $ Currently 1.000+ readers https://leanpub.com/javaparservisited Federico Tomassetti See you on GitHub at javaparser/javaparser