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

后端 未结 1 1849
小蘑菇
小蘑菇 2020-12-17 04:10

If I create a custom annotation (example: @SaveFuncName(\"saveMe\") will add a method called saveMe() with some code my processor generates), can t

相关标签:
1条回答
  • 2020-12-17 04:57

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

    0 讨论(0)
提交回复
热议问题