我正在编写自己的注释处理器,并且我正在尝试获取注释的参数,如下面的处理方法中的代码所示:
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/