This is the first part of the Playing With args4j series. For your convenience you can find other parts using the links below (or by guessing the address):
Part 1 — Mixins
Part 2 — Automatic getters

Imagine that you are working on a command line tool and you need to parse arguments somehow. You can use pretty nice library called args4j.

So you write a class for your job parameters:

And then you parse it:

Looks great. Some time later you write another job with another parameter:

Time goes by and you need to write another job which should have both of the parameters. What can you do? This is Java so you can’t use multiple inheritance of state. However, there are default interface implementations which we can use to simulate mixins!

Let’s start with this:

We create an interface with methods for getting and setting parameters. We also have one abstract method providing collection. We could use field here but then it would be static so we wouldn’t be able to create multiple instances at the same time.

Now, let’s rework first parameter class:

The same goes for second parameter class:

Now we need to have an implementation for collection:

One more thing: we need to have concrete classes with parameters but this is trivial:

Awesome… but it doesn’t work. The reason is that args4j doesn’t support methods on interfaces — it just doesn’t parse them. Let’s fix that:

Yep, that was long but now we are ready to create class for third job:

Done! I believe you can clearly see the advantages and that doing that in such a simple example is not very beneficial but can be great if you have multiple combinations of parameters for different jobs.

There is one terrible thing, though. Instead of having one field we need to have two methods now. We will fix that one day.