How to Auto-Generate Repetitive Java Code to Save Your Time

DN Tech
Geek Culture
Published in
5 min readMar 12, 2022

--

Scenario

You are asked to design an order management application. Whenever a client creates an order, it could be in different forms — a new order, a cancel order, a modify order… each data object with different fields or different values. When the business expands, there are going to be more variations of the orders, leading to repetitive programming. How can you save your time by inputting the necessary changes only once and the code can be generated once and for all?

In this article, we are going to leverage JavaPoet API, a JSON file, and some maven plugins to help us auto-generate code based on customized input into another microservice.

Project setup

To start with, I have a blank maven project in my project directory and created a package called code-generator.

And then I created another package called order-management so that we could use the generated code for our business purposes.

Import dependencies

The only dependencies for code-generator are javapoet for code generation and json-simple for reading JSON file.

<dependencies>
<dependency>
<groupId>com.squareup</groupId>
<artifactId>javapoet</artifactId>…

--

--

DN Tech
Geek Culture

Backend Software Engineer who shares about my daily work bits