相关疑难解决方法(0)

如何在 Kotlin 数据类字段上列出(java)注释?

我使用 Firestore 的基于 Java 的注释来标记字段和将文档字段映射到 Java 类元素的方法:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface PropertyName {
  String value();
}
Run Code Online (Sandbox Code Playgroud)

我在 Kotlin 数据类的一个字段上使用它,它编译得很好:

data class MyDataClass(
    @PropertyName("z") val x: Int
)
Run Code Online (Sandbox Code Playgroud)

在 IntelliJ 和 Android Studio 中,我可以看到它出现在反编译的类转储中:

public final data class MyDataClass public constructor(x: kotlin.Int) {
    @field:com.google.cloud.firestore.annotation.PropertyName public final val x: kotlin.Int /* compiled code */

    public final operator fun component1(): kotlin.Int { /* compiled code */ }
}
Run Code Online (Sandbox Code Playgroud)

在这一点上,我的印象是这个注释应该可以通过 Kotlin 反射以某种方式被发现。据我所知,事实并非如此。我试过迭代注释:

  1. 每个 Kotlin 数据类构造函数字段
  2. 每个 Kotlin 字段
  3. 每个 Kotlin 函数
  4. 每个 Java …

reflection jvm annotations kotlin

4
推荐指数
2
解决办法
5156
查看次数

标签 统计

annotations ×1

jvm ×1

kotlin ×1

reflection ×1