Kotlin 从注释中获取静态字段的值
我想从声明的注释的静态字段中获取值。 例如: 我希望得到“test123”作为值 到目前为止,我可以从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
元素
中获得名称和种类,如下所示:
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
注释仅指定字段,则无需确保字段上存在注释;如果注释不在字段上,则常规编译器检查将捕获。也就是说,验证字段是否是编译时常量可能会有所帮助。