注释处理工具 <- 检查有效的注释 [英] Annotation Processing Tool <- checking valid annotation

查看:29
本文介绍了注释处理工具 <- 检查有效的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

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

而且我必须使用 APT 检查索引号是否唯一.我不知道该怎么做.教程看不懂,一般网上找资料有问题.

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.

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

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

推荐答案

您可能想要使用可插入注释 API,它是 apt 工具的继承者.这是一个简短的入门教程:Java 6.0 特性第 – 2 部分:可插入注解处理 API

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. 创建一个注解处理器,它应该扩展抽象处理器.
  2. 定义要查找的注释,添加:
    @SupportedAnnotationTypes(value= {"full.name.of.ColumnMetadata"})
  3. 覆盖 process 方法.
  4. 使用 RoundEnvironment 参数访问源代码的元素.你需要什么元素取决于你想做什么.
    • 自上而下的方法:getRootElements 提供了所有类,您可以过滤要检查的特定元素.如果您想分析注释周围的代码结构,例如您的方法或属性注释所在的类,则此方法很有用.
    • 自下而上的方法:getElementsAnnotatedWith 使用此方法仅获取带注释的元素.您可以推断元素的位置,但如果您想比较它们,则可能需要跟踪您的元素(例如,通过将带注释的元素列表映射到类类型).
  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).

这篇关于注释处理工具 <- 检查有效的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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