Wednesday, October 21, 2009

How to use an annotation.

Defining an annotation type
To define an annotation type called Meta:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public @interface Meta {
String data() default "fast";

Using an annotation
To use that annotation:

@Meta(data = "slow")
public void foo(){

Using the annotation meta data ("calm down dear, it's only an example").
To print out the meta data that the annotation defines for the example above:

public static void main(String[] args) {
for (Method method : MyClass.class.getMethods()) {
Annotation[] annotations = method.getAnnotations();
int num = annotations.length;

No comments: