Search code examples
kotlinreflectionannotationsdata-class

How to filter data class properties by kotlin annotation?


Implimentation of Annotation

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

Dummy Data class

data class DataClass(
    val property: String
    @Returnable
    val annotatedProperty: String
)

Java Reflections filtering doesn't work

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

Solution

  • Kotlin annotation isn't the same as Java annotations. So work with Kotlin reflection requires a bit different way compare to classic java. Here you can find a way of filtering properties of Kotlin data class by Kotlin annotations

    DataClass("false","true")::class.members.filter {
         it.findAnnotation<Returnable>() != null
    }