Using reflection for command line option parsing

Over the last few days I have needed a few command line tools -- mostly for data cleanup. I got tired of manually parsing command line arguments. I wanted something more automated. My first thought was to design a data-structure that expressed the command lines arguments then write an interpreter that would parse the arguments with its guidance. I spent an hour doing this only to realize that preparing the data-structure was almost as much work as manual parsing. Then I remembered that Ant has a simple facility that uses reflection to execute a task expressed in XML against an object. This is what I wanted. So, for example, the command line tool
java ... Sum --multiplier 25 --verbose 1 2 3 4
would be implemented as

public class Sum implements Runnable {

public void setVerbose() {
this.verbose = true;

public void setMultiplier( Long multiplier ) {
this.multiplier = multiplier;

public void addPositional( Long number ) {

public void run() {
long sum = 0;
for ( Number number : this.numbers } {
if ( verbose ) {
System.out.printf("%d + %d= %d\n",
sum + number.longValue() );
sum += number.longValue();
if ( this.multiplier != null ) {
if ( verbose ) { ... }
sum *= multiplier;



The magic, of course, is reflection. The reflection-based parser sees "--verbose" and matches it against setVerbose(), "--multiplier" matches against setMultiplier() and that it takes one numeric option. The remaining positional arguments are passed to addPositional() as numbers. Once parsed run() is called. The ReflectiveCommandLineParser is used to handle the magic within the main()
   public static void main( String[] args ) {
Sum sum = new Sum();,args);
See ListFiles implementation for another example.