Writing and processing custom annotations - Part 2
In this article, we will take a first step toward this goal by developing a custom annotation call @Option.
Developing the @Option Annotation
Annotations
are nuggets of information that we embed in our Java program; these information
can then be used by tools and other Java applications during compilation or
runtime to configure databases or generate other classes for example. You can
think of annotations as comments to be read by other programs.
Let us look at how one might write an annotation:
- Write an interface; however the interface keyword must be precede by an at (@) sign like so: @interface
- Methods must not have any parameters or throw any exception
- The return types of the methods are restricted to all Java primitives, String, Class, enums, annotations, and arrays of all the types we have just mentioned
- You have the option of specifying default values.
Here is an example of how our @Option annotation looks like when we use it:
@Option(switch="-filename") |
this is how we write the annotation
public
@interface Option { |
Note that the help method has a default value.
When you are developing an annotation, you also need to specify the following
two things:
- What is this annotation going to annotate? You need to specify if you are going to use your annotation to annotate classes or members or methods or parameters, etc, or a combination of these. To do this, we use the @Target to annotate @Option
- Where should an annotation be retained? The choices here are source, class or runtime. Retention affects the visibility of an annotation. The @Retention annotation is used to specify where annotations are stored.
If you recall, our @Option only annotates members; furthermore we will not need the annotation beyond compilation viz. once we have generated the command line processor class. So your final annotation looks like this:
java.lang.annotation.*; |
One final note: Notice
that @Target and @Retention do not use the parameter=value format. This is because in
single valued annotations like the pair mentioned above, you can omit the
parameter.
Find out more on annotations in JSR175.
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.