4

If I create a custom annotation (example: @SaveFuncName("saveMe") will add a method called saveMe() with some code my processor generates), can the javac compiler use my annotation processor to add a method to the class? Or can I only create a different class?

Don Rhummy
  • 20,170
  • 31
  • 134
  • 252

1 Answers1

8

Or can I only create a different class?

That's correct. The existing API doesn't let us modify existing classes, just generate new ones.

Technically speaking, if you want to do some hacky stuff, it's possible to use internal Javac API to modify the abstract syntax tree directly but it's not for the faint of heart. For example, an object like TypeElement is actually a symbol directly from Javac, hidden from us by the interface. The syntax tree is also available in a read-only mode through the compiler tree API. We can cast the interfaces away and modify the code that way. This is how e.g. Project Lombok works.

(But I can't recommend doing this. I'm mostly explaining it because Lombok is a thing that exists so it looks like modifying classes is possible.)

The easiest solutions are to do something like generate a superclass with e.g. saveMe() methods and extend it or generate a utility class and delegate to it. (Also suggested here.)

Community
  • 1
  • 1
Radiodef
  • 35,285
  • 14
  • 78
  • 114
  • Since Oracle is featuring Lombok in their May 2017 "Java Magazine"... does that mean they are in favour of hacky stuff or would consider allowing APT to change the current file? That question brought me here when reading the article, because Lombok seemed to do just that. But i guess there's no elegant way to build that into the APT API and you would need to edit the AST anyway. – Stroboskop May 30 '17 at 08:01
  • @Stroboskop It's hacky because it's undocumented so you have to go read the javac source code to figure out how stuff works. It could be that the author of that article just isn't aware of what Lombok is doing behind the scenes. Lombok has their own blurb about it if you want to see what they say: http://jnb.ociweb.com/jnb/jnbJan2010.html#controversy Personally I hope modifying the AST, or at least just adding methods, is added as a feature but I doubt it will happen any time soon. – Radiodef May 30 '17 at 13:37