Search code examples
javakotlinreflectionannotations

Java annotation cannot be found per reflection on a Kotlin data class


Given this Java annotation

@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonProperty

and this Kotlin data class

@JsonIgnoreProperties(ignoreUnknown = true)
data class LossDocument(@JsonProperty("id") val id: String)

I would expect to find the annotation either here

LossDocument::class.java.declaredFields[0].annotations

or here

LossDocument::class.java.declaredMethods.first { it.name == "getId" }

but both have zero annotations. Is this a bug? Per 53843771, my impression is this should work. I'm using Kotlin 1.4.0.

When I declare the annotation explicitly as @field:JsonProperty("id") I can find it without problem using LossDocument::class.java.declaredFields[1].annotations.


Solution

  • 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

    In your case the annotation is placed on the constructor parameter.