The more advanced uses of annotations include writing an annotation processor that can read a Java program and take actions based on its annotations. To make annotation information available at runtime, the annotation type itself must be annotated with @Retention(RetentionPolicy.RUNTIME)
The following example will create one Utility Class for processing the annotation, one class for defining the annotation and a third class to use the annotation and processor class.
Example:-
(1) HelloAnnotation Class.
package com.visualbuilder;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface HelloAnnotation
{
}
(2) Utility Class.
package com.visualbuilder;
import java.lang.reflect.Field;
public class Utility {
public static <T> void inject(Class<T> resolveeClass, T resolveeInstance) {
Field[] fields = resolveeClass.getFields();
if (fields != null) {
for (Field field : fields) {
if (field.getAnnotation(HelloAnnotation.class) != null) {
try {
field.set(resolveeInstance, "Hello, Annotation World!");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
}
(2) CustomAnnotation Class.
package com.visualbuilder;
public class CustomAnnotation {
@HelloAnnotation
public String hello;
public static void main(String[] args) {
CustomAnnotation object=new CustomAnnotation();
Utility.inject(CustomAnnotation.class,object);
System.out.println(object.hello);
}
}
Output
The following output will be displayed.
Hello, Annotation World!
Java Discussion
- - Java web application
- - Difference between BMT an
- - Replace getParameterValue
- - Interviewing Next week -
- - Sudoku solver





