Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 804
Michael Böckling Avatar asked Oct 27 '25 06:10

Michael Böckling


1 Answers

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.

like image 153
Mafor Avatar answered Oct 29 '25 21:10

Mafor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!