【问题标题】:Get value of static field from annotation从注解中获取静态字段的值
【发布时间】: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


【解决方案1】:

你可以使用VariableElement#getConstantValue():

如果这是一个初始化为编译时常量的final 字段,则返回此变量的值。否则返回null。该值将是原始类型或String。如果值是原始类型,则将其包装在适当的包装类中(例如Integer)。

请注意,并非所有final 字段都具有常量值。特别是,enum 常量被认为是编译时常量。要具有常量值,字段的类型必须是原始类型或 String

回报:
如果这是一个初始化为编译时常量的final 字段,则为该变量的值,否则为null

请参阅 Java 语言规范
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.FIELD 转换为VariableElement 将起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 2010-12-02
    • 2011-11-07
    相关资源
    最近更新 更多