Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 从注释中获取静态字段的值_Kotlin_Annotations_Annotation Processor - Fatal编程技术网

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

Kotlin 从注释中获取静态字段的值,kotlin,annotations,annotation-processor,Kotlin,Annotations,Annotation Processor,我想从声明的注释的静态字段中获取值。 例如: 我希望得到“test123”作为值 到目前为止,我可以从元素中获得名称和种类,如下所示: for (element: Element in environment?.getElementsAnnotatedWith(TestAnnotation::class.java)!!) { if (element.kind != ElementKind.FIELD) { messager?.error("@TestAnnotation mus

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

我希望得到“test123”作为值

到目前为止,我可以从
元素
中获得名称和种类,如下所示:

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”?

您可以使用:

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

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

返回:
如果这是初始化为编译时常数的
final
字段,或
null
字段,则为该变量的值

参见Java语言规范:

您必须将
元素
强制转换为
可变元素
。例如:

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
将起作用。

您可以使用:

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

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

返回:
如果这是初始化为编译时常数的
final
字段,或
null
字段,则为该变量的值

参见Java语言规范:

您必须将
元素
强制转换为
可变元素
。例如:

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
转换到
variablelement
将起作用。

请注意:如果
@Target
注释仅指定字段,则无需确保注释出现在字段上;如果注释不在字段上,则常规编译器检查将捕获。这就是说,验证字段是否是编译时常量可能会有所帮助。请注意:如果
@Target
注释仅指定字段,则无需确保字段上存在注释;如果注释不在字段上,则常规编译器检查将捕获。也就是说,验证字段是否是编译时常量可能会有所帮助。