Playing With args4j Part 3 — Nice setters

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

Let’s see how we can implement the setters. Idea is as following: we will pass a lambda indicating the getter of the parameter. Next, we will create a dynamic proxy using cglib, call the getter (which should have no side effects) and then we will intercept the actual call to extract the getter method. Next, we will parse the annotation and call the setter.

First, we add the magical setter:

We accept three parameters: lambda representing the getter, value to set, and a class representing the object. We extract the getter method, get its annotation and execute the normal setter.

Next, we implement the reflection magic:

We create an enhancer to capture the call. Next, we execute the lambda (which is a getter), capture it and store the reference. Finally, we return the method.

Now we can call it like this:

And this works like a charm.