Java 无法在 Kotlin 数据的每个反射中找到注释 class
Java annotation cannot be found per reflection on a Kotlin data class
鉴于此 Java 注释
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonProperty
和这个 Kotlin 数据 class
@JsonIgnoreProperties(ignoreUnknown = true)
data class LossDocument(@JsonProperty("id") val id: String)
我希望能在这里找到注释
LossDocument::class.java.declaredFields[0].annotations
或此处
LossDocument::class.java.declaredMethods.first { it.name == "getId" }
但两者的注释均为零。这是一个错误吗?根据 ,我的印象是这应该有效。我正在使用 Kotlin 1.4.0.
当我将注释显式声明为 @field:JsonProperty("id")
时,我可以使用 LossDocument::class.java.declaredFields[1].annotations
.
毫无问题地找到它
When you're annotating a property or a primary constructor parameter, there are multiple Java elements which are generated from the corresponding Kotlin element, and therefore multiple possible locations for the annotation in the generated Java bytecode.
If you don't specify a use-site target, the target is chosen according to the @Target annotation of the annotation being used. If there are multiple applicable targets, the first applicable target from the following list is used:
param, property, field. -- Annotation Use-site Targets
在你的例子中,注释被放置在构造函数参数上。
鉴于此 Java 注释
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonProperty
和这个 Kotlin 数据 class
@JsonIgnoreProperties(ignoreUnknown = true)
data class LossDocument(@JsonProperty("id") val id: String)
我希望能在这里找到注释
LossDocument::class.java.declaredFields[0].annotations
或此处
LossDocument::class.java.declaredMethods.first { it.name == "getId" }
但两者的注释均为零。这是一个错误吗?根据
当我将注释显式声明为 @field:JsonProperty("id")
时,我可以使用 LossDocument::class.java.declaredFields[1].annotations
.
When you're annotating a property or a primary constructor parameter, there are multiple Java elements which are generated from the corresponding Kotlin element, and therefore multiple possible locations for the annotation in the generated Java bytecode.
If you don't specify a use-site target, the target is chosen according to the @Target annotation of the annotation being used. If there are multiple applicable targets, the first applicable target from the following list is used: param, property, field. -- Annotation Use-site Targets
在你的例子中,注释被放置在构造函数参数上。