1

I've got an extension method running on Any type. On that extension method (where this refers to the target instance), I'm trying to filter the memberProperties based on annotation presence.

this::class.memberProperties
        .filter{ it.annotations.map { ann -> ann.annotationClass }.contains(ValidComponent::class)}

But it.annotations is always of size 0

Example of variable declaration on the instance: @ValidComponent var x: SomeType = constructorParam.something or @ValidComponent lateinit var x: SomeType

ntakouris
  • 898
  • 1
  • 9
  • 22

1 Answers1

0

This is an issue with what the annotations are applied to. If you had an annotation with a target of "property", your code would list them just fine:

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
annotation class ValidComponent

I assume your annotation has a "field" target instead, in which case you'll have to jump through Java reflection to list the annotations on your properties:

this::class.memberProperties
        .filter { property ->
            val fieldAnnotations = property.javaField?.annotations
            fieldAnnotations != null && fieldAnnotations.map { ann -> ann.annotationClass }.contains(ValidComponent::class)
        }
zsmb13
  • 85,752
  • 11
  • 221
  • 226