Handling Repeated Code Automatically

Learn how to deal with repeated Java code automatically!

In this article, I will describe how you can use the Java::Geci generator Repeated to overcome the Java language shortage that generics cannot be primitive. The example is a suggested extension of the Apache Commons Lang library.

When you copy-paste code, you do something wrong. At least that is the perception. You have to create your code structure in a more generalized way so that you can use different parameters instead of similar code many times.

Reflection Selector Expression

Java::Geci is a code generator that runs during unit test time. If the generated code fits the actual version of the source code, then the test does not fail. If there is a need for any modification, then the tests modify the source code and fail. For example, there is a new field that needs a setter and getter. Then, the accessor generator will generate the new setter and getter and then it fails. If there is no new field, then the generated code is just the one that is already there — no reason to touch the source code: The test that started the generator finishes successfully.

Because Java::Geci generators run as tests, which is at run-time, and because they need access to the Java code structures for which they generate code, Java reflection is key for these generators.