Kotlin reflection: findAnnotation<Type>() returns null

Viewed 1216

I have the following data class:

data class Foo(@field:Password val password: String)

Why does Foo::password.annotations return an empty list? Also, Foo::password.findAnnotation<Password>() returns null.

The same happens when I use an instance of Foo:

Foo("")::password.annotations

Foo("")::password.findAnnotation<Password>()

However, this java variant works: Foo::password.javaField.getAnnotation(Password::class.java).

This is on kotlin version 1.3.10.

The docs don't give much information on the inner workings of findAnnotation.

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-property/index.html

fun <T : Annotation> KAnnotatedElement.findAnnotation(): T?

Returns an annotation of the given type on this element.

What am I missing here?

Thanks in advance!

1 Answers

Foo::password.annotations is the list of annotations on the property. In your code, you've used the @field: use site target, which means that the annotation is applied to the backing field, not the property. Therefore, the list of annotations on the property is empty.

The Java variant works because it loads the list of annotations on the field.

Related