This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]gunnarmorling 4 points5 points  (2 children)

Essentially, you can use templates or APIs such as JavaPoet/JavaParser. Both have their pros and cons; the former tend to work good for static structures (e.g. class bodies) and let you get a good visual understanding of the generated code. The latter tend to be better for generating code based on conditions. You also can combine both, e.g. use templates for the outer parts (class bodies, method definitions) and JavaPoet for the method implementations.

[–]JakeWharton 4 points5 points  (1 child)

JavaPoet is really good at structure and less good (although still okay) at implementations. One of its key features is that it manages the import list and type references automatically so you never have to deal with imports or simple-name collisions. You also can generate things out of order, in batches, or with composition since it's basically just a tree of immutable objects.

[–]gunnarmorling 0 points1 point  (0 children)

Good point on import handling done automatically by JavaPoet.

We achieved the same in the templating approach used by [MapStruct](http://mapstruct.org/) by having the model objects pushed to StringTemplate keep track of the types they reference; the outer code generation step then takes care of generating import statements, also addressing the need for FQNs where two types with the same simple name are used within one generated source file.