javacode-generation

Automatically generating Java source code


I'm looking for a way to automatically generate source code for new methods within an existing Java source code file, based on the fields defined within the class.

In essence, I'm looking to execute the following steps:

  1. Read and parse SomeClass.java
  2. Iterate through all fields defined in the source code
  3. Add source code method someMethod()
  4. Save SomeClass.java (Ideally, preserving the formatting of the existing code)

What tools and techniques are best suited to accomplish this?

EDIT

I don't want to generate code at runtime; I want to augment existing Java source code


Solution

  • Modifying the same java source file with auto-generated code is maintenance nightmare. Consider generating a new class that extends you current class and adds the desired method. Use reflection to read from user-defined class and create velocity templates for the auto-generating classes. Then for each user-defined class generate its extending class. Integrate the code generation phase in your build lifecycle.

    Or you may use 'bytecode enhancement' techniques to enhance the classes without having to modify the source code.

    Updates:

    1. mixing auto-generated code always pose a risk of someone modifying it in future to just to tweak a small behavior. It's just the matter of next build, when this changes will be lost.
    2. you will have to solely rely on the comments on top of auto-generated source to prevent developers from doing so.
    3. version-controlling - Lets say you update the template of someMethod(), now all of your source file's version will be updated, even if the source updates is auto-generated. you will see redundant history.