Software Engineering
java templates code-generation
Updated Wed, 07 Sep 2022 15:31:07 GMT

How to generate java class files with framework boilerplate in a project?

The Java project I am working on currently has a complicated folder structure, and to add a new functionality, one needs to add many .java files in different places in order to let it work in our project structure. For example, when I want to add a new object User, I need to add Entity, JsonModel, Controller, Listener, Publisher.., etc. It'd be easily missed if handled manually, so I'm looking for some way to automatically generate .java files dedicated to one same object in different paths on demand.

For example, the programmer set the tool to generate .java files about User and it generates UserEntity, UserInputModel... into fit places, and then the programmer go write the actual code for those .java files.

Is there a common way to handle this problem in Java? Maybe a famous tool, or some framework? I also ain't quite sure what's the keyword I should look for on this question. Code Generation doesn't seem to mean the same, while Generate Classes leads to the similar discussions. They're both more about automatically coding or transforming natural languages into actual codes. But here I just want to automate the .java file creations, not the code in them.

I am not native English speaker, so I hope if you can, please also point me to the right word on this topic.


I think the word you're looking for is a template. Most IDEs support some kind of template mechanism; specifically in the Java world, if you happen to use IntelliJ, it supports multi-file templates that solve your exact problem. You can create a template that includes boilerplate code for all the classes you want to generate, using a variable for the object name. When you instantiate the template, it will create a bunch of files and replace the variable with the name you specify.

If you don't use IntelliJ or need to do something fancier, you can also build a custom solution based on one of the common template languages out there (IntelliJ itself uses Velocity, but there are many other options out there).

Comments (1)

  • +1 – This is exactly the solution I am currently look for. Thank you very much! Not sure why someone downvoted this though, I am curious for reason. — Jul 22, 2022 at 06:45