我使用 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 反射以某种方式被发现。据我所知,事实并非如此。我试过迭代注释: