Sunday, October 31, 2010

Java Annotations

One of the coolest things that java permits to do, is add annotations on classes and methods.
This feature can extremely useful, for example build your how unit of tests or something else.

The interface is here you define or annotation.

import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Annotation {
String name();
String description();
}
view raw gistfile1.java hosted with ❤ by GitHub


And in your class.

@Annotation(name="Something", description="This is a annotation")
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> klass = Class.forName("Main");
Annotation annotation = (Annotation) klass.getAnnotation(Annotation.class);
System.out.println("Annotation " + klass);
System.out.println("name: " + annotation.name());
System.out.println("Version: " + annotation.description());
}
}
view raw gistfile1.java hosted with ❤ by GitHub


Output

Annotation class Main
name: Something
Version: This is a annotation

No comments: