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.

Bothered by SLOW Web UI to manage vSphere? Want to manage ALL your VMware vCenters, AWS, Azure, Openstack, container behind a SINGLE pane of glass? Want to search, analyze, report, visualize VMs, hosts, networks, datastores, events as easily as Google the Web? Find out more about vSearch 3.0: the search engine for all your private and public clouds.

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.");
This entry was posted in Software Development and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.


  1. Chris
    Posted July 29, 2014 at 12:59 am | Permalink

    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. Posted May 20, 2015 at 3:31 pm | Permalink

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

  3. Posted May 20, 2015 at 4:23 pm | Permalink

    Hi Federico, thanks for sharing the information!


Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.