Java Annotation, also known as Java Annotations or Java Markers, is a metadata mechanism introduced in JDK5.0 that allows programmers to add annotations (metadata) to program elements like classes, methods, variables, parameters, and packages. Unlike comments or Javadoc, which are ignored by compilers, Java annotations can be preserved in compiled bytecode and can be utilized by various tools, such as code analyzers, build tools, and frameworks.
Here is an example of how to use Java annotations for parsing:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
int value();
}
public class MyClass {
@MyAnnotation(42)
private String myField;
public void parseAnnotations() {
Field[] fields = MyClass.class.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
System.out.println("Value of annotation: " + annotation.value());
}
}
}
}