我可以从编译时注释向类添加方法吗? [英] Can I add a method to a class from a compile time annotation?

查看:37
本文介绍了我可以从编译时注释向类添加方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个自定义注释(例如:@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.)

这篇关于我可以从编译时注释向类添加方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆