Wednesday, April 27, 2011

Creating custom annotations in java


Here are some rule to consider when defining an annotation type:
  1. Annotation declaration should start with an 'at' sign like @, following with an interface keyword, following with the annotation name.
    eg.
    public @interface MyAnnotation
  2. Method declarations should not have any parameters.
  3. Method declarations should not have any throws clauses.
  4. Return types of the method should be one of the following:
    • primitives
    • String
    • Class
    • enum
    • array of the above types


Example to Define an Annotation (Annotation Type)

public @interface MyAnnotation {
   String doSomething();
}

Example to Annotate Your Code (Annotation)

MyAnnotation (doSomething="What to do")
public void mymethod() {
   ....
}

No comments:

Post a Comment

Chitika