Can I add a method to a class from a compile time annotation?
Asked Answered
P

1

7

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?

Prate answered 12/4, 2016 at 4:46 Comment(0)
A
11

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.)

Amidase answered 12/4, 2016 at 22:11 Comment(2)
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.Henrion
@Henrion 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: 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.Amidase

© 2022 - 2024 — McMap. All rights reserved.