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 ) { this.numbers.add(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() ); } sum += number.longValue(); } if ( this.multiplier != null ) { if ( verbose ) { ... } sum *= multiplier; } System.out.println(sum); } ... }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(); ReflectiveCommandLineParser.run(sum,args); }
See ListFiles implementation for another example.