5

I know that the Annotation Processor is normally used to consume annotations and react to them. I, however, have a use case where this "reaction" involves adding other annotations. Can this be done within the processor itself? If so, how?

Eric
  • 1,343
  • 1
  • 11
  • 19

1 Answers1

2

The short answer is yes, and you don't have anything specific to do.

An annotation processor is used to create new source files, not to modify existing ones. So when you say "adding other annotations", I guess you mean "creating new classes that hold annotations".

Annotation processing is done in rounds. At each round, the process method of your annotation processor is called.

If a processor generate new source files, another round of annotation processing starts

  • newly generated source files are parsed and annotations are processed as before
  • processors invoked on previous rounds are also invoked on all subsequent rounds

So basically : you have nothing to do, it already works ;-) .

Pierre-Yves Ricau
  • 8,209
  • 2
  • 27
  • 43
  • Thanks so far but actually I was hoping that there would be a way to alter the existing source files, adding new annotations there. Is that possible as well? – Eric Jun 17 '11 at 08:53
  • No, not with annotation processing. Annotation Processing can only be used to create new files. – Pierre-Yves Ricau Jun 18 '11 at 06:22
  • 1
    However, you could modify the bytecode to add annotations (see ASM for instance), or add those annotations through reflection at runtime (see [AnnotationInjector](http://thecodersbreakfast.net/index.php?post/2011/02/20/Introducing-AnnotationInjector)) – Pierre-Yves Ricau Jun 18 '11 at 06:26