View RSS Feed

My Java Tips

Custom annotations - default values

Rate this Entry
by , 10-31-2011 at 05:40 PM (1184 Views)
I'll focus on setting some default values for the annotation.


Yes, you want the users to specify values for the annotations but only if their values differ some default values. Default values should be provided to make things easier.

The following example shows how one can associate default values with custom annotations.

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

// Annotation type with default values
public @interface GroupTODO {

  public enum Severity { CRITICAL, IMPORTANT, TRIVIAL, DOCUMENTATION };

  Severity severity() default Severity.IMPORTANT;
  String item();
  String assignedTo();
  String dateAssigned();
}
The annotation named GroupTODO is declared with new variables. It doesn't have a single-member variable,




In the example given , a new feature was used which demonstrates that the annotation type defines its own enumeration. Enumerations are usually just called enums and are another new feature of Java 5. The following example uses the new enumeration as the type for the member variable.

Establishing default values for annotations is pretty easy. You just add the keyword default at the end of the member declaration, and then supply the default value. Ofcourse, the default value must be the same type that you declared for the member variable.

The followign example uses GroupTODO annotation:

Java Code:
// Taking advantage of default values
  @com.domain.tiger.a.InProgress
  @GroupTODO(
    item="Figure out the amount of interest per month",
    assignedTo="M Clark",
    dateAssigned="08/04/2008"
  )
  public  void calculateInterest(float amount, float rate) {
    // code code goes here
  }

The following example shows the same annotation as given in the previous example, in use. This time with a value supplied for severity:

Java Code:
// Overriding default values
  @com.domain.tiger.a.InProgress
  @GroupTODO(
    severity=GroupTODO.Severity.DOCUMENTATION,
    item="Need to explain how this rather unusual method works",
    assignedTo="M Clark",
    dateAssigned="08/04/2008"
  )
  public  void reallyConfusingMethod(int codePoint) {
    // code goes here
Happy codding!

Submit "Custom annotations - default values" to Facebook Submit "Custom annotations - default values" to Digg Submit "Custom annotations - default values" to del.icio.us Submit "Custom annotations - default values" to StumbleUpon Submit "Custom annotations - default values" to Google

Tags: None Add / Edit Tags
Categories
Annotations

Comments