Playing With args4j Part 4 — Nicer setters

This is the fourth 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 ended with the setter of a form

. What we don’t like here is the last parameters — why would we want to pass the class type if we pass the method reference? Can we extract it somehow?

In theory we cannot but with some help of unsafe methods we will be able to do so. Beware — this is not production ready, this is just for fun.

We will need the Unsafe library to make it a little easier. We could go with using sun.misc.unsafe directly but this library does that and gives nice interface so we can use it.

First, we need to change the lambda type:

So we get the Supplier which points to the method directly. Next, we get the target from the lambda. This is how we do it:

My JVM version running on Windows 10 Enterprise x64 is:

This explains why we get the 4 bytes pointer.

Next, we need to modify the cglib logic:

So now we get the type by calling getClass and then we modify the target of the lambda. We use pointer arithmetic once again to do that:

Thanks to that we can now write: