How to create custom annotation in Java
Annotations were introduced in JDK 1.5 and act like meta data. In this tutorial, we will see how to create a new annotation and then use it in other classes. The following code shows how to create annotation in Java.
public @interface MyAnnotation {
public String str1();
public String str2();
}
In order to apply the above annotation to a class, one has to use the following code:
public class NewClass {
@MyAnnotation(
str1="abc", str2="1.0")
public void test() {
}
}
One has many options like allowing the annotation to be applied to class, methods or variables only. We can also make the annotation to behave at compile time or runtime.
One can use annotation processor for defining how the annottaion will behaving by using the Processor interface as shown on the following link:
http://docs.oracle.com/javase/6/docs/api/javax/annotation/processing/Processor.html
No comments:
Post a Comment