Automatically Generate Java Source Code

I am looking for a way to automatically generate source code for new methods in an existing Java source file based on fields defined in a class.

In essence, I want to follow these steps:

  • Read and parse SomeClass.java
  • Iterate through all fields defined in the source code
  • Add someMethod() source code method
  • Save SomeClass.java (Ideally, save the formatting of existing code)

What tools and techniques are best suited for this?

EDIT

I do not want to generate code at runtime; I want to increase existing Java source code

+4
source share
7 answers

Changing the same java source file using automatically generated code is a maintenance nightmare. Consider creating a new class that extends your current class and adds the desired method. Use reflection to read from a custom class and create speed patterns for classes that generate cars. Then, for each user-defined class, an extensible class is generated. Integration of the code generation phase in the assembly life cycle.

Or you can use bytecode improvement methods to improve classes without changing the source code.

Updates:

  • mixing auto-generated code always poses the risk that someone will change it in the future to just tweak the little behavior. It is just a matter of the next build when these changes are lost.
  • you will have to rely solely on comments on top of an automatically generated source so that developers do not.
  • version control. Suppose you updated the someMethod () template, now your entire version of the source file will be updated, even if the original updates are automatically generated. You will see a redundant story.
+2
source

What you want is the Transformation Program .

Good ones have parsers for the language you are interested in, assembling the AST, representing the program for the analyzed code, will give you access to the AST for analysis and modification, and can restore the source text from the AST. Your remark about "field scanning" is just a kind of workaround for the AST representing the program. For each interesting analysis result that you produce, you want to make changes to the AST, perhaps somewhere else, but nonetheless in the ACT. And after you have created all the variables, you want to restore the text with comments (as it was originally entered, or as you built in your new code).

There are several tools that are specifically designed for Java.

Jackpot provides a parser, builds AST, and allows you to code Java procedures to do what you want with trees. Potential: simple conceptually. Downside: You write a lot more Java code to climb trees than you expected. The jackpot only works with Java.

Stratego and TXL analyze your encode, create AST and let you write surce-to-source transformations (using the target language syntax, like Java in this case) to express patterns and corrections. Additional useful news: you can define any programming language that you like as the target language for processing, and both of them have Java definitions. But they are weak in analysis: often you need character plates and data flow analysis to really analyze and modify what you need. And they insist that this whole rewrite rule is whether this helps you or not; it's a bit like you only need a hammer in the toolbox; in the end, everything can be seen as a nail, right?

Our DMS Software Reengineering Toolkit allows you to define an inaccurate target language (and has many predefined langauges, including Java ), includes all the possibilities of converting a source to a Strategyo source, TXL, Jackpot procedural capabilities, and additionally provides symbol tables, control and flow analysis data data. The compiler guys taught us that these things are necessary to create strong compilers (= "analysis + optimization + refinement"), and this is true for code generation systems for exactly the same reasons. Using this approach, you can generate code and optimize it to the extent that you have the knowledge to do so. One example similar to your serialization ideas is the generation of fast XML readers and writers for specific XML DTDs; we did this using DMS for Java and COBOL.

DMS is used to read / modify / write many types of source files. A good example that makes ideas clear can be found in this technical article, which shows how to modify the code for inserting measurement probes: Branch Coverage Made Easy . A simpler but more complete example of the definition of arbitrary lanauges and the transformations applicable to it can be found in How to Transform Algebra using the same ideas.

+11
source

Take a look at Java Emitter Templates . They allow you to create java source files using a markup language. This is similar to how you can use a scripting language to spit out HTML, except that you spit out the compiled source code. The JET syntax is very similar to the JSP, and therefore not too difficult to pick up. However, this may be redundant for what you are trying to achieve. Here are some resources if you decide to go this route:

+4
source

You can use cglib to generate code at runtime.

+2
source

Iterating over the fields and defining someMethod is a rather vague task, so it's hard to give you a very useful answer, but Eclipse refactoring support provides some great tools. It will provide you with constructors that initialize the selected set of specific members, and it will also define the toString method for you.

I do not know what other someMethod () you would like to consider, but there is a beginning for you.

+1
source

I would be very wary of entering the generated code into files containing handwritten code. Handwritten code should be checked in version control, but the generated code should not be; code generation should be performed as part of the build process. You will have to structure the build process so that for each file you make a temporary copy, paste the generated source code into it and compile the result without touching the original source file that developers are working on.

+1
source

Antlr is a great tool that can be very easily used to convert Java source code to Java source code.

+1
source

All Articles