注释处理工具<-检查有效注释

发布于 2024-12-21 17:31:15 字数 216 浏览 4 评论 0 原文

@ColumnMetadata(index=1)
...
@ColumnMetadata(index=2)
...
@ColumnMetadata(index=3)
...

必须使用 APT 检查索引号是否唯一。我不知道该怎么做。我看不懂教程,一般在网上找资料都遇到问题。

如何做到这一点?有任何关于 APT 的教程/任何内容吗?

I have

@ColumnMetadata(index=1)
...
@ColumnMetadata(index=2)
...
@ColumnMetadata(index=3)
...

And I have to check whether index numbers are unique using APT. I have no idea how to do this. I don't understand tutorials, generally I have problem to find materials on the net.

How to do this? Any tutorials/anything about APT?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

栖竹 2024-12-28 17:31:15

您可能想要使用可插入注释 API,它是 apt 工具的后继者。这是一个简短的入门教程: Java 6.0 功能第 - 2 部分:可插入注释处理 API

这大致是检查注释所需执行的步骤:

  1. 创建一个注释处理器,它应该扩展 AbstractProcessor
  2. 定义要查找的注释,添加:
    @SupportedAnnotationTypes(value= {"full.name.of.ColumnMetadata"})
  3. 重写 process 方法。
  4. 使用 RoundEnvironment 参数访问源代码的元素。您需要什么元素取决于您想要做什么。
    • 自上而下的方法:getRootElements 提供所有类,您可以过滤这些类以查找要检查的特定元素。如果您想分析注释周围的代码结构(例如您的方法或属性注释所在的类),此方法非常有用。
    • 自下而上的方法:getElementsAnnotatedWith 使用此方法仅获取带注释的元素。您可以推断元素的位置,但如果您想比较它们,可能需要跟踪元素(例如,通过将带注释的元素列表映射到类类型)。
  5. 循环您想要的元素并获取 注释镜像获取 并检查值。
  6. 如果要报告错误,请使用提供的 Messager 与元素。您可以使用它在 IDE 中创建漂亮的编译器错误消息。

You probably want to use the pluggable annotation API, the successor of the apt tool. Here's a short tutorial to get started: Java 6.0 Features Part – 2 : Pluggable Annotation Processing API

This are roughly the steps you need to do to check your annotations:

  1. Create a annotation processor, it should extend AbstractProcessor.
  2. Define which annotations to look for, add:
    @SupportedAnnotationTypes(value= {"full.name.of.ColumnMetadata"})
  3. Override the process method.
  4. Use the RoundEnvironment parameter to access the elements of the source code. What elements you need depends on what you want to do.
    • Top-down approach: getRootElements provides all classes, which you could filter for particular elements you want to check. This method is useful if you want to analyse the code structure around your annotations, for example the class your method or property annotations are in.
    • Bottom-up approach: getElementsAnnotatedWith Use this method to get only annotated elements. You can infer the position of the elements but may need to keep track of your elements if you want to compare them (for example by mapping a list of annotated elements to a class type).
  5. Loop over the elements you want and get the AnnotationMirror. Get and check the values.
  6. If you want to report an error, use the provided Messager with the element. You can create nice compiler error messages in your IDE with this.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文