We have relaunched: What's new at ZDNet Asia?

Writing and processing custom annotations - Part 4

Summary

Check out the final part of this series of articles on annotations.

Events

Microsoft MSDN/Developer Event
25 Mar 2010

One Marina Boulevard, Microsoft Singapore

IT Architect Regional Conference Singapore 2010
20 - 21 Apr 2010

Singapore Management University, Singapore

The Internet Show 2010
21-22 Apr 2010

Suntec Singapore

We have finally arrived at our last and final part of this series of articles on annotations.

In the previous three articles (part 1, part 2 and part 3), we saw how to design and develop a custom annotation; we also looked at how to write a processor to handle the custom annotation. Now we come to the part where we put all these elements together and see how to use them. Finally, if you are interested in developing this @Option annotation further, I'll give some suggestions at the end of this article.

Using the @Option Annotation
In the first article are details on how to use the @Option annotation and generate the option processor, so I will not repeat them here. I will, however, talk about packaging and environment settings.

  1. The easiest way to distribute our annotation and its corresponding processor is to package it in a JAR file. Generally you package the annotation class, the annotation processor class and all utility classes used by the processor. In our case, we have only 2 classes to package, options.Option.class and options.OptionProcessor.class
  2. When you are annotating your option bean with the @Option annotation, you have to either add the annotation JAR to your CLASSPATH environment variable or as a classpath parameter when you are compiling the option bean.
  3. Now, when you are generating the option processor class, you have to again either include the annotation JAR in your CLASSPATH environment variable or use-classpath option to javac. You will also need to specify the name of the processor class by using the -processor option. Unfortunately at the time of writing, this option has yet to be documented on the official Java 6 (a.k.a Mustang) Javadocs. Below is an example of using -processor option:

javac -processor options.OptionProcessor -classpath ./options.jar \
   FileTransferOptions.java

The FileTransferOptions.java is our option bean; the options.OptionProcessor is our option processor fully qualified class name. Note that we use-processor to specify the option processor class to use. Assume that options.jar is where we package the annotation and processor class.
The class FileTransferOptionsProcessor will be generated after the compilation. You can now use this class to process all the option switches defined in FileTransferOptions. Again see the first article on how you use this.

You can find the entire source for options processor (plus sample option bean and test classes) here.

Going Further
The options processor developed in this series of articles is quite simplistic. If you are interested in developing it further, here are some ideas:

  1. Error checking is not done on the option switches. The generated option processor will just ignore any switches that it did not understand. Add error handling so that the option processor will print out the list of options and its corresponding help string, if any, when it encounters an error.
  2. Auto generate a help switch (-help) so that it will print out the list of supported options and its corresponding help string, if any.

java Main -help
The options are
   -filename - Text file name
   -config - Configuration file
   -server

  1. Currently the option processor only supports String; rewrite the option processor so that it supports all primitive types. The option processor should look at the type in the option bean and automatically convert the option value to the corresponding type. Here is an example:

public class MyOptions {
   @Option(name="-filename") public String fileName;
   @Option(name="-copies", help="Number of copies") public int copies;
   @Option(name="-header", help="Print header? y|n") public boolean printHeader;
   @Option(name="-printer") public String printServer;
}

Now if we type the following

java Main -filename fred.txt -copies 2 -header n -printer myprinter

then 2 and n will be converted to the integer value 2 and false respectively.

  1. Support for multi-valued options. In the code snipped below -filename is multivalued; this is inferred from the String array

public class MyOptions {
   @Option(name="-filename") public String[] fileName;
   @Option(name="-copies", help="Number of copies") public int copies;
   ...

The following are two ways of how you specify multivalued options:

java Main -filename fred.txt barney.txt -header n -printer myprinter

or

java Main -filename fred.txt -filename barney.txt -header n -printer myprinter

  1. Regular expression support

public class MyOptions {
   @Option(name="^-[Ff][Ii][Ll][Ee][[Nn][Aa][Mm][Ee]]*", re=true) public String[] fileName;
   @Option(name="-copies", help="Number of copies") public int copies;
   ...

The following are then valid options

java Main -FileName fred.txt -file barney.txt -header n -printer myprinter

  1. If there is anything else you care to implement, here are some suggestions: validators, mutually exclusive options and option switch only viz. specify -debug to enable the debug option instead of -debug y

Lee Chuk-Munn has been programming in the Java language since 1996, when he first joined Sun Microsystems in Hong Kong. He currently works as a senior developer consultant and technology evangelist for Technology Outreach at Sun in Singapore. Chuk's focus is in Java APIs, Java EE, Java SE, and Java ME. Chuk graduated in 1987 from the Royal Melbourne Institute of Technology in Melbourne, Australia, where his favorite subject was compiler theory.

Talkback

Add your opinion

In order to post a comment, you need to be registered. (Sign In or register below)

Post your comment
Transform your business interactions with real-time voice, video and telepresence solutions.
Tech Vendor: Cisco

ZDNet Asia Live

www.3w.com.au has seen it's outsourced IT Contracting Business in Manila grow at 4 times the rate of its traditional Australian Based...

3 minutes ago by brucemills on Companies' outsourcing spend to increase

RT @3wconsulting: Whitepaper from http://3W.com.au "Outsourcing Your IT Requirements to Philippines" now on @zdnetaustralia & @zdnetasia http://ow.ly/1oY9f

Whitepaper from http://3W.com.au "Outsourcing Your IT Requirements to Philippines" now on @zdnetaustralia & @zdnetasia http://ow.ly/1oYbA

Whitepaper from http://3W.com.au "Outsourcing Your IT Requirements to Philippines" now on @zdnetaustralia & @zdnetasia http://ow.ly/1oYbz

Zdnetasia.com Estimated Worth $178,365 USD. Daily Ad Revenue:$244 USD, Daily Views:81,445 Pages... - http://www.haplog.com/www.zdneta...

recently estimated website net worth of zdnetasia.com - http://www.haplog.com/www.zdneta...

9 hours 56 minutes ago by haplog on topsy

When I create an event, I click on an approximate time during the day when I want the event to occur, then I click "edit event detail...

1 day 32 minutes ago by bessellbrowne on Google Calendar gets 'smart' rescheduling

ipads break alott i had one it broke three times in the month i had it so i got rid of the damn thing id just go for the laptop Top Grade...

1 day 34 minutes ago by bessellbrowne on Report: 'Hundreds of thousands' of iPad preorders

There are a number of websites that still require Internet Explorer to view and IE for Mac Stinks (it is really ies4osx which is the Wind...

1 day 35 minutes ago by bessellbrowne on Microsoft: Only minor tweaks in Windows 7 SP1

The receivers don't transmit back to the satellite. Unless there is a phone line attached to the receiver, they don't have any wa...

1 day 38 minutes ago by bessellbrowne on Apple to join the geolocation craze?

What to expect from open source Symbian http://is.gd/aPIGL

1 day 53 minutes ago by rebelk0de on topsy

"Lead Cognos BI Developer Insurance - Jobs - ZDNet Asia" http://bit.ly/bRcxOG

1 day 33 minutes ago by rhrcognos on topsy

whatever little understanding I have we 'll only progress toward end of the world if we use HPCs to lenthen life of human being. Huma...

1 day 45 minutes ago by abhi32002@gmail.com on High computing promises elixir of life

Thanks for the knowledgeable article on SDDs. Allas...when all this reasearch will happen in Indian Universities. Hope the new bill on Fo...

1 day 58 minutes ago by abhi32002@gmail.com on APAC HPC users eye solid-state drives

It was a good article. This brings a good opportunity for Indian IT firms to come up with new solutions in this field. HPC can become a b...

1 day 16 minutes ago by abhi32002@gmail.com on High computing most-wanted job in Asia

COL KR DHARMADHIKARY(RETD) its very late to reply the link, but if it is still alive and looking for opportunity, i would like to know th...

1 day 14 minutes ago by deb021280 on Education takes off in rural India, helped by PCs

It was just a matter of time until google was marginalised anyway. I'm afraid this will be forgotten in China very quickly. Still, it...

1 day 18 minutes ago by robinsmith on Report: Google to leave China on April 10

High performance computing (HPC) most-wanted job in Asia http://bit.ly/9vFC3i (via @zdnetasia) #singapore

He doesn't care if her shoes are of glass, All he wants to see is a huge rack and nice a*s. Sleeping beauty's not awoken by true ...

1 day 47 minutes ago by warlowdavies on One pair of 3D glasses to rule them all

RT @zdnetasia: EMC COO, Pat Gelsinger, on bridging gaps in the organization and its cloud ambitions in Asia. (cont) http://tl.gd/i5jjd

EMC COO, Pat Gelsinger, on bridging gaps in the organization and its cloud ambitions in Asia. http://bit.ly/9etOZW

Asian SMBs need to pay more attention to disaster recovery planning http://bit.ly/bDet08 via @zdnetasia

Asian SMBs need to pay more attention to disaster recovery planning http://bit.ly/bDet08

[TECH] URL Shorteners slow Web redirection. - http://bit.ly/bySnWK @zdnetasia

URL shorteners are great but they can slow web redirection & you pray it would never go down http://bit.ly/bySnWK via @zdnetasia

Temasek Holdings eyeing tech stocks, indicating optimistic outlook on IT sector. http://bit.ly/aM7VwU

URL shorteners slow Web redirection. http://bit.ly/bySnWK

Chinese agencies cry foul over Google. http://bit.ly/by6rwV

all of sg's isps have been practising compulsory invisible proxy for all home subscribers at their backend since many years back alre...

2 days 57 minutes ago by melvinchia on Web filters mean bad news for business

it is not to good for china.
Proactol

3 days 42 minutes ago by nathonastle on Chinese ad partners beg Google for information

IT security insiders rob casinos of $50K http://is.gd/aPIKR

3 days 14 minutes ago by rebelk0de on topsy

Very good explanation of JMX

3 days 47 minutes ago by Babith B on Managing applications with JMX

The reaction to a report issued Tuesday by Flurry Analytics managed to completely overlook some interesting news--the Android-based Motorola Droid outsold the original iPhone over the same period of time following their respective launches--to focus instead on the sales numbers for the Nexus One.

4 days 51 minutes ago by lonemavericks on diggs

Another ZTE story....

4 days 53 minutes ago by Moderate Your Greed on Philippines opens bid for final 3G license