Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotation Processing Tool <- checking valid annotation

I have

@ColumnMetadata(index=1)
...
@ColumnMetadata(index=2)
...
@ColumnMetadata(index=3)
...

And I have to check whether index numbers are unique using APT. I have no idea how to do this. I don't understand tutorials, generally I have problem to find materials on the net.

How to do this? Any tutorials/anything about APT?

like image 403
OnTheFly Avatar asked Feb 22 '23 03:02

OnTheFly


1 Answers

You probably want to use the pluggable annotation API, the successor of the apt tool. Here's a short tutorial to get started: Java 6.0 Features Part – 2 : Pluggable Annotation Processing API

This are roughly the steps you need to do to check your annotations:

  1. Create a annotation processor, it should extend AbstractProcessor.
  2. Define which annotations to look for, add:
    @SupportedAnnotationTypes(value= {"full.name.of.ColumnMetadata"})
  3. Override the process method.
  4. Use the RoundEnvironment parameter to access the elements of the source code. What elements you need depends on what you want to do.
    • Top-down approach: getRootElements provides all classes, which you could filter for particular elements you want to check. This method is useful if you want to analyse the code structure around your annotations, for example the class your method or property annotations are in.
    • Bottom-up approach: getElementsAnnotatedWith Use this method to get only annotated elements. You can infer the position of the elements but may need to keep track of your elements if you want to compare them (for example by mapping a list of annotated elements to a class type).
  5. Loop over the elements you want and get the AnnotationMirror. Get and check the values.
  6. If you want to report an error, use the provided Messager with the element. You can create nice compiler error messages in your IDE with this.
like image 70
kapex Avatar answered Mar 03 '23 11:03

kapex