【发布时间】:2020-05-13 22:31:32
【问题描述】:
我想从声明的注释中的静态字段中获取值。 示例:
@TestAnnotation
const val MY_CUSTOM_FIELD = "test123"
我想将“test123”作为值。
到目前为止,我可以像这样从Element 获取名称和种类:
for (element: Element in environment?.getElementsAnnotatedWith(TestAnnotation::class.java)!!) {
if (element.kind != ElementKind.FIELD) {
messager?.error("@TestAnnotation must be applied to field")
return true
}
val typeMirror = element.asType()
messager?.error(elements?.getName(element.simpleName).toString()) // this prints MY_CUSTOM_FIELD
messager?.error(typeMirror.toString()) // this prints java.lang.String
}
是否有可能以某种方式获得“test123”?
【问题讨论】:
-
请注意:如果
@Target注释仅指定字段,则不需要确保字段上存在注释;如果注释不在字段上,则正常的编译器检查将捕获。话虽如此,验证该字段是否为编译时常量可能会有所帮助。
标签: kotlin annotations annotation-processor