java - 如何在注释处理器中获取注释参数

标签 java kotlin annotations annotation-processing

我正在编写自己的注释处理器,并且我正在尝试获取注释的参数,如下面的处理方法中的代码所示:

roundEnv.getElementsAnnotatedWith(annotation).forEach {
        val annotation = it.getAnnotation(annotation)
        annotation.interfaces
}

我得到的是发生异常:javax.lang.model.type.MirroredTypesException:在构建期间尝试访问TypeMirrors []的类对象。有人知道如何获取注释数据吗?

最佳答案

关于 getAnnotation 的文档方法解释原因Class<?>对象对于注释处理器来说是有问题的:

The annotation returned by this method could contain an element whose value is of type Class. This value cannot be returned directly: information necessary to locate and load a class (such as the class loader to use) is not available, and the class might not be loadable at all. Attempting to read a Class object by invoking the relevant method on the returned annotation will result in a MirroredTypeException, from which the corresponding TypeMirror may be extracted. Similarly, attempting to read a Class[]-valued element will result in a MirroredTypesException.

要访问类等注释元素,您需要使用 Element.getAnnotationMirrors()并手动查找感兴趣的注释。这些注释镜像将包含代表实际值的元素,但不需要存在相关类。

关于java - 如何在注释处理器中获取注释参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54962817/

相关文章:

java - Jenkins API : EnvVars. overrideAll 不会覆盖管道作业中的现有环境变量。

android - Kotlin 覆盖抽象 val 行为,对象与类

spring-boot - Spring Boot Gradle Kotlin构建

java - 注释是 Java 中的某种 DSL 吗?

java - 可用的java注释重载吗?

java - 创建 10 个/100 个 Guice 注入(inject)器是否被认为是不好的实践/设计?

java - 将 GWT 项目导入 IntelliJ 失败

eclipse - eclipse kotlin插件会编译kotlin代码吗?

java - 使用注释(Inject、Autowired)或使用 getBean 在 Spring 中创建对象

java - python 无法从网络打印解压的 float