DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones Build AI Agents That Are Ready for Production
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
Build AI Agents That Are Ready for Production

LIVE: “Cognitive Databases, Intelligent Data: Unified Infrastructure for Vector Search, AI-Optimized Queries, & Hybrid Workloads" Report

Join this live webinar to learn safer rollout techniques for schema changes, index testing, and database migrations.

Live Webinar: Exclusive practitioner summit on AI-powered CDN operations and real-world automation strategies

Related

  • Jakarta NoSQL: Why JPA Is Not Enough for the AI Era
  • Top Java Security Vulnerabilities and How to Prevent Them in Modern Java
  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j

Trending

  • Intelligent Matching and Semantic Search for Marketplace Applications Using OpenAI and .NET
  • Amazon CodeWhisperer to Q Developer to Kiro: The Rise of Agentic Coding
  • The Latency Tax That’s Hidden in Cloud-Native Systems (and the Hard Lessons I Learned to Minimize It)
  • Spring AI Advisors: Chat Memory, Token Tracking, and Message Logging
  1. DZone
  2. Coding
  3. Java
  4. JavaParser: Java Code Generation

JavaParser: Java Code Generation

Looking to learn more about using the JavaParser in your projects?

By 
Prasanth Mohan user avatar
Prasanth Mohan
·
Updated Feb. 20, 19 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
30.2K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, I'm going to show you how to generate Java code using theJavaParser. I couldn't find much of the documentation available with regards to code generation in javaparser.org or the manual. So, I thought putting this out would help someone who would like to experiment with the Java parser.

In its simplest form, the JavaParser library allows you to interact with Java source code as a Java object representation in a Java environment. More formally, we refer to this object representation as an Abstract Syntax Tree (AST). Also, it has the ability to manipulate the underlying structure of the source code. This can then be written to a file, providing developers with the facility to build their own code generating software.

First up, you have to instantiate the compilation unit, upon which you will add the remaining pieces of the code.

CompilationUnit compilationUnit = new CompilationUnit();


Then, you can add your import statements to the compilation unit, here:

compilationUnit.addImport("org.springframework.boot.SpringApplication");


You can add your package statement to the compilation unit, as shown below:

compilationUnit.setPackageDeclaration("com.abc.def");


You can add the class declaration to the Java file:

ClassOrInterfaceDeclaration classDeclaration = compilationUnit.addClass("AnyClassName").setPublic(true);

 

If you want to add annotations at the class level, you can use the following code:

classDeclaration.addAnnotation("AnyAnnotation");


You can add method declarations within your newly declared class, as shown below:

MethodDeclaration methodDeclaration = classDeclaration.addMethod("anyMethodName", PUBLIC);
methodDeclaration.setType("AnyReturnType");


You can add arguments to your newly created method declaration:

methodDeclaration.addAndGetParameter(String.class, "args").setVarArgs(true);


Add annotations on top of the newly declared method:

methodDeclaration.addAndGetAnnotation("AnyAnnotation");


To add the method logic/block statement within the newly declared method, use the below code:

BlockStmt blockStmt = new BlockStmt();
methodDeclaration.setBody(blockStmt);


To declare and instantiate a variable within the method/block statement, use the following code:

ExpressionStmt expressionStmt = new ExpressionStmt();
VariableDeclarationExpr variableDeclarationExpr = new VariableDeclarationExpr();
VariableDeclarator variableDeclarator = new VariableDeclarator();
variableDeclarator.setName("anyVariableName");
variableDeclarator.setType(new ClassOrInterfaceType("AnyVariableType"));
variableDeclarator.setInitializer("new AnyVariableType()");
NodeList<VariableDeclarator> variableDeclarators = new NodeList<>();
variableDeclarators.add(variableDeclarator);
variableDeclarationExpr.setVariables(variableDeclarators);
expressionStmt.setExpression(variableDeclarationExpr);

blockStmt.addStatement(expressionStmt);


To invoke a method of the new variable created within the method/block statement, use the below code:

NameExpr nameExpr = new NameExpr("anyVariableName");
MethodCallExpr methodCallExpr = new MethodCallExpr(nameExpr, "anyMethodName");
methodCallExpr.addArgument("anyArgument");

blockStmt.addStatement(methodCallExpr);


To return the variable created in the method, use the code below:

ReturnStmt returnStmt = new ReturnStmt();
NameExpr returnNameExpr = new NameExpr();
returnNameExpr.setName("anyVariableName");
returnStmt.setExpression(returnNameExpr);

blockStmt.addStatement(returnStmt);


To print the code generated above, just call the toString method of the compilation unit:

String code = compilationUnit.toString();


To add an annotation with multi-valued key value pairs, use the below code.

NodeList<Expression> annotationParamValueList = new NodeList<>();
annotationParamValueList.add(new StringLiteralExpr("Value1");
annotationParamValueList.add(new StringLiteralExpr("Value2");
ArrayInitializerExpr annotationParamValueArrayInitializerExpr = new ArrayInitializerExpr(annotationParamValueList);
Name annotationName = new Name("AnyAnnotationName");
NodeList<MemberValuePair> annotationParamList = new NodeList<>();
MemberValuePair memberValuePair = new MemberValuePair();
memberValuePair.setName(new SimpleName("AnyValue"));
memberValuePair.setValue(annotationParamValueArrayInitializerExpr);
annotationParamList.add(memberValuePair);
AnnotationExpr annotationExpr = new NormalAnnotationExpr(annotationName, annotationParamList);


Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Jakarta NoSQL: Why JPA Is Not Enough for the AI Era
  • Top Java Security Vulnerabilities and How to Prevent Them in Modern Java
  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook