In the following test, the field id of class TestData is marked with the annotation Foo. Why is the output of .annotations and .findAnnotation() empty though?
How can check if a field is annotated by a certain annotation?
I asked this as well on reflection - Finding field annotations using obj::class.declaredMemberProperties - Stack Overflow but got no answer. Is it the same bug as https://youtrack.jetbrains.com/issue/KT-10837 although I don’t have “use-site” annotations?
import kotlin.test.Test
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.findAnnotation
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class MissingAnnotationTest {
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class Foo
data class TestData(@Foo val id: Int)
@Test
fun test() {
val obj = TestData(123)
val idProp = obj::class.declaredMemberProperties.first { it.name == "id" }
println("# property: " + idProp) // "val ...TestData.id: kotlin.Int"
println("# annotations: " + idProp.annotations) // [] - but why?
println("# findAnnotations<Foo>: " + idProp.findAnnotation<Foo>()) // null - but why?
assertTrue(idProp.name.endsWith("TestData.id: kotlin.Int"))
assertEquals(1, idProp.annotations.size, "Bug! No annotations found!")
assertNotNull(idProp.findAnnotation<Foo>())
}
}