Annotations   «Prev  Next»

Annotations Project

The 3 classes in the project are
  1. MyClassAnnotation
  2. MyRuntimeAnnotation
  3. MySourceAnnotation

Annotation processor that executes during the compilation of the source file. Create another file called MyClassAnnotation.
Create another file using the Class Retention Policy.

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

@Retention(RetentionPolicy.CLASS)
public @interface MyClassAnnotation {
}

This is an annotation with a Class Retention Policy. The annotation information is retained in the generated class file.
// MyRuntimeAnnotation 
Time 1:42 
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyRuntimeAnnotation {
}

We can get information about the Annotation at Runtime using Java Reflection methods. Let us create a class that uses all 3 of these annotations. Create a class in the source folder.

The class TestingAnnotatedClasses.java is in a directory that is 1 higher than the annotation packages.
The class TestingAnnotatedClasse is part of the default package.
public void showAnnotations(Object e) {
returns the declared annotations for each of these elements.
public void printRuntimeAnnotations() {
  Class c = this.getClass();
  showAnnotations(c);
  for (Method method : c.getDeclaredMethods()) {
   showAnnotations(method);
  }
  for (Field field : c.getDeclaredFields()) {
   showAnnotations(field);
  }
}

Here is the output of the program
Class Annotation: @annotations.MyRuntimeAnnotation()
// Apply annotations to the class