Playing With args4j Part 2 — Automatic getters

This is the second part of the Playing With args4j series. For your convenience you can find other parts in the table of contents in Part 1 – Mixins

Last time we created mixins to be able to compose classes with multiple inherited parameters. We immediately noticed that we have a lot of code duplication because we need to specify parameter names in multiple places. In this part we will see how to cut the boilerplate.

We will implement custom Setter to automatically populate the fields. Here it is:

In addValue we just call a bean method populating the dictionary. How do we get the name of the parameter? In this way:

We just extract the name from the Option annotation.

Now we can simplify the parameters and remove redundant methods:

We still specify annotation with name and usage. We also need to specify a default value which we do by calling the method get which is:

So we get the stack trace and look for the first method with the Option annotation (remember about inlining!). When we find it, we just extract the parameter value as usual.

So we still have a strongly typed parameter with getter, and setter is created automatically. So we can do that:

And this returns the value of the parameter. However, to set the parameter, we need to do this:

So we need to have the name again. Can we do better? We will see in the next part.