使用kotlinpoet-metadata从构造函数值参数获取注释

时间:2020-04-26 03:07:33

标签: kotlinpoet

我有这样的数据类

@Tagme("Response")
@TagResponse
data class Response(
    val id: Int,
    val title: String,
    val label: String,
    val images: List<String>,

    @Input(Parameter::class)
    val slug: Slug
)

使用注释处理器,我可以使用以下方法获取Response属性:

val parentMetadata = (element as TypeElement).toImmutableKmClass()

parentMetadata.constructors[0].valueParameters.map { prop ->

   // this will loop through class properties and return ImmutableKmValueParameter
   // eg: id, title, label, images, slug.

   // then, I need to get the annotation that property has here.
   // eg: @Input(Parameter::class) on slug property.

   // if prop is slug, this will return true.
   val isAnnotationAvailable = prop.hasAnnotations

   // Here I need to get the annotated value
   // val annotation = [..something..].getAnnotation(Input::class)
   // How to get the annotation? So I can do this:
   if ([prop annotation] has [@Input]) {
      do the something.
   }
}

以前,我试图获得这样的注释:

val annotations = prop.type?.annotations

但是,即使isAnnotationAvailable的值为true,我也得到了空列表

谢谢!

1 个答案:

答案 0 :(得分:1)

仅当注释在其他地方无法存储时,才将其存储在元数据中。对于参数,必须直接从Parameter(反射)或VariableElement(元素API)中读取它们。这就是为什么我们有ClassInspector API的原因。除了基本类数据之外,您几乎永远不想尝试读取任何其他内容。字节码或元素中已经包含的任何内容基本上也不会复制到元数据中。将元数据视为添加的信号,而不是批量替换。

相关问题