Using SimpleTemplateEngine to generate files during compilation

Rohit Gupta
2 min readFeb 24, 2024
Gradle logo

I want to share two very interesting use cases I’ve come across throughout my journey as an Android engineer.

The first was where I automated the process of generating several project’s readme files. We had to maintain around twenty different libraries with releases going out each month. With that came the task of bumping the version in the project’s readme and update any new dependencies if added. It was tedious and it desperately needed automation.

The second was where we had to generate a class out of a json file. The json file had some key design variables which is not something you’d want to keep in your BuildConfig class as it would be semantically incorrect. The json had to be parsed into a class and had to be packaged during compilation.

Both these use cases were solved by using Groovy’s SimpleTemplateEngine.

Using SimpleTemplateEngine you can create files from a defined template through gradle tasks. I’ve created a sample project which lets you create a new config class similar to Android’s BuildConfig using SimpleTemplateEngine and a little gradle magic. You can find it here

Below you can find the crux of the implementation.

  1. Create a template for your class which you want to generate. You can pass properties such as strings, arrays and maps to this template. You can learn more about the syntax here

2. Create a new gradle task which will create the java file out of this template. The properties which the template will use are passed through expand

Here out_dir is the directory where you’ll create your file. I’m setting the output directory to build/generated/source.

3. You also have to tell the compiler to look for your autogenerated class to compile and package into your apk. You can do that by the following code in your build.gradle

Once you’ve got these steps covered, all that remains is to execute your task. You can mark this task dependent on any other task before the application is packaged. For convenience, I’ve marked this task dependent on preBuild as there isn’t any dependencies my task need and I’d like it to get executed during the start of the build process.

Voila! You just leveraged SimpleTemplateEngine to autogenerate a java class! All that remains is to build your project. Once done, this is what the autogenerated class looks like

You can use the same logic to create a readme file or any other use cases that you might come across. Have fun! 👋

--

--

Rohit Gupta

Android developer @Publicis Sapient. ♥️ video games, tech, cyberpunk and sci fi literature.