我可以从编译时注释向类添加方法吗?
如果我创建自定义注释(例如: @SaveFuncName(saveMe)
将添加一个名为 saveMe()的方法
使用我的处理器生成的一些代码),javac编译器可以使用我的注释处理器向类添加方法吗?或者我可以只创建一个不同的类吗?
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?
或者我可以只创建一个不同的类吗?
Or can I only create a different class?
这是正确的。现有的API不允许我们修改现有的类,只需生成新的类。
That's correct. The existing API doesn't let us modify existing classes, just generate new ones.
从技术上讲,如果你想做一些hacky的东西,可以使用内部的Javac用于直接修改抽象语法树的API,但它不适合胆小的人。例如,像 TypeElement
这样的对象实际上是一个直接来自Javac的符号,接口对我们隐藏了。语法树也可通过编译器树API 。我们可以抛弃接口并以这种方式修改代码。这就是例如 Project Lombok 可以使用。
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.
(但我不建议这样做。我主要是在解释它,因为Lombok是一个存在的东西所以看起来修改类似乎是可能的。)
(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.)
最简单的解决方案是执行类似生成超类的操作 saveMe()
方法并对其进行扩展或生成实用程序类并委托给它。 (还建议此处。)
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.)