View RSS Feed

My Java Tips

Defining own annotation type

Rate this Entry
by , 10-31-2011 at 06:49 PM (1689 Views)
The Java language supports defining new annotation types. An annotation type looks similar to an ordinary class, but it has some unique properties. One can use it with the at sign in the classes to annotate your other Java code.

Its right to say that defining a new annotation type is similar to creating an interface. We have to precede the interface keyword with the @ sign.

The following example shows the simplest possible annotation type:

Java Code:
package com.domain.tiger.a;

 * Marker annotation to indicate that a method or class
 *   is still in progress.
public @interface InProgress { }
Compile this annotation type and put it in your classpath. Now the annotation is ready to be used in the source code methods.

I will use the inProgress annotation declared above.

The following example uses the declared custom annotation.

Java Code:
public void calculateInterest(float amount, float rate) {
  // Need to finish this method later
Thing to note is that we use the custom annotation type exactly the same way as we use the built-in annotation types. Only difference is that we indicate the custom annotation by both its name and package.
You may import the annotation type and refer to it as simply @InProgress.

Submit "Defining own annotation type" to Facebook Submit "Defining own annotation type" to Digg Submit "Defining own annotation type" to Submit "Defining own annotation type" to StumbleUpon Submit "Defining own annotation type" to Google

Tags: None Add / Edit Tags