View RSS Feed

My Java Tips

Custom annotations - Adding a member

Rate this Entry
by , 10-31-2011 at 05:45 PM (763 Views)
Annotation types can have member variables. You will understand its importance when you use annotations for metadata, not just raw documentation. These member variables provides very useful information to code-analysis tools.




Data members in annotation types are set up to work using limited information. The way to add member is to define a single method that should be named after the member which you want to allow for. The data type should be the return value of the method.

Review the example below:

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

/**
 * Annotation type to indicate a task still needs to be
 *   completed.
 */
public @interface TODO {
  String value();
}



In the previous example, I declared a custom annotation type which defines a string named value that the annotation type can accept. The following example shows how to use an annotation type with a member value:

Java Code:
@com.domain.tiger.a.InProgress
@TODO("Figure out the amount of interest per month")
public void calculateInterest(float amount, float rate) {
  // Need to finish this method later
}
It is assumed that com.domain.tiger.a.InProgress has been imported which means that we don't prefix the annotation with its package name.

Submit "Custom annotations - Adding a member" to Facebook Submit "Custom annotations - Adding a member" to Digg Submit "Custom annotations - Adding a member" to del.icio.us Submit "Custom annotations - Adding a member" to StumbleUpon Submit "Custom annotations - Adding a member" to Google

Tags: None Add / Edit Tags
Categories
Annotations

Comments