Home > Software Development > Parsing, Modifying, and Generating Java Source Code With Javaparser

Parsing, Modifying, and Generating Java Source Code With Javaparser

It’s not common to do something with Java source code programmatically, but I find the javaparser project is very handy if such a use case comes up. It’s a Java 1.5 parser with AST generation and visitor support. With the API, you can access various elements in the source code like class, methods, statements, javadoc, comments, etc.

You can also change these elements and save into a new file. This essentially allows source transformation or generation. In one recent project, I used it to read in Java interface source code, and generate implementation code. You may wonder why not use Java Reflection APIs. Although Java Reflection APIs works just fine, it’s not easy to generate meaningful parameter names. Using javaparse to read an interface source code, modify it, and save it to a new source code file, I can preserve the most useful aspects of the interface code.

Lost VMs or Containers? Too Many Consoles? Too Slow GUI? Time to learn how to "Google" and manage your VMware and clouds in a fast and secure HTML5 App.

The javaparse is pretty easy to use if you are familiar with the visitor design pattern. The creators of the project has also good documentation with a few samples.
. It does cover basic use cases. While using the API, I did find myself using extra APIs that is not covered in the examples, therefore had to do quite some search in various forums and sometimes read javadoc. Here are a few more small samples.

Add Import Statement
The following code inserts a new import statement into the compilation unit. To avoid loss of existing import statements, it first gets the imports and add them into the list, which is then set on the compilation unit.

CompilationUnit cu;
ImportDeclaration id = new ImportDeclaration();
id.setName(new NameExpr("org.doublecloud.parserdemo.*"));
List<ImportDeclaration> idList = new ArrayList<ImportDeclaration>();

Change Visibility

The following code changes the method visibility to public. In other words, it would add public in front of the method name. Following the direction, you can also add other keywords.

MethodDeclaration method;

Add Comments

The line comments start with double slash in Java. You can add one line comment as follows.

NameExpr clazz = new NameExpr("System");
FieldAccessExpr field = new FieldAccessExpr(clazz, "out");
MethodCallExpr call = new MethodCallExpr(field, "println");
ASTHelper.addArgument(call, new StringLiteralExpr("hello doublecloud"));
ASTHelper.addStmt(block, call);
LineComment comment = new LineComment("TODO: Time to DoubleCloud");

You can also add a block comment like this:

ClassOrInterfaceDeclaration cid;
cid.setComment(new BlockComment("Copyright 2014, DoubleCloud.");
  1. Chris
    July 29th, 2014 at 00:59 | #1

    Did you ever write the file back out after altering it? I’ve found that compilationUnit.toString() doesn’t preserve whitespace. I was wondering if you ran into that too? If so, did you find a solution?

  2. May 20th, 2015 at 15:31 | #2

    Nice post, thank you for writing about JavaParser. Note that now it supports Java 8

  3. May 20th, 2015 at 16:23 | #3

    Hi Federico, thanks for sharing the information!


  1. No trackbacks yet.