从注释中获取静态字段的值

Get value of static field from annotation

我想从声明的注释的静态字段中获取值。 示例:

@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"?

您可以使用 VariableElement#getConstantValue():

Returns the value of this variable if this is a final field initialized to a compile-time constant. Returns null otherwise. The value will be of a primitive type or a String. If the value is of a primitive type, it is wrapped in the appropriate wrapper class (such as Integer).

Note that not all final fields will have constant values. In particular, enum constants are not considered to be compile-time constants. To have a constant value, a field's type must be either a primitive type or String.

Returns:
the value of this variable if this is a final field initialized to a compile-time constant, or null otherwise

See Java Language Specification:
15.28 Constant Expression
4.12.4 final Variables

您必须将 Element 转换为 VariableElement。例如:

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 constant = (element as VariableElement).constantValue;
}

请注意,由于 element.kind == ElementKind.FIELDVariableElement 的转换将起作用。