Java Reference
In-Depth Information
You can get the fully qualified name of an annotation using the
getQualifiedName()
method of the
TypeElement
interface.
Name qualifiedName = currentAnnotation.getQualifiedName();
// Check if it is a Version annotation
if (qualifiedName.contentEquals("com.jdojo.annotation.Version")) {
// Get Version annotation values to validate
}
Once you are sure that you have a
Version
annotation, you need to get all its instances from the source code. To
get information from the source code, you need to use the
RoundEnvironment
object. The following snippet of code
will get all elements of the source code (e.g. classes, methods, constructors, etc.) that are annotated with a
Version
annotation:
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(currentAnnotation);
At this point, you need to iterate through all elements that are annotated with a
Version
annotation; get the
instance of the
Version
annotation present on them; and validate the values of the
major
and
minor
elements. You
can perform this logic as follows:
for (Element element : annotatedElements) {
Version v = element.getAnnotation(Version.class);
int major = v.major();
int minor = v.minor();
if (major < 0 || minor < 0) {
// Print the error message here
}
}
You can print the error message using the
printMessage()
method of the
Messager
object. The
processingEnv
is an instance variable defined in the
AbstractProcessor
class that you can use inside your processor to get the
Messager
object reference, as shown below. If you pass the source code element's reference to the
printMessage()
method, your message will be formatted to include the source code file name and the line number in the source code
for that element. The first argument to the
printMessage()
method indicates the type of the message. You can use
Kind.NOTE
and
Kind.WARNING
as the first argument to print a note and warning, respectively.
String errorMsg = "Version cannot be negative. " +
"major=" + major + " minor=" + minor;
Messager messager = this.processingEnv.getMessager();
messager.printMessage(Kind.ERROR, errorMsg, element);
Finally, you need to return
true
or
false
from the
process()
method. If a processor returns
true,
it means it
claimed all the annotations that were passed to it. Otherwise, those annotations are considered unclaimed and they
will be passed to other processors. Listing 1-23 has the complete code for the
VersionProcessor
class.