matrixguy
matrixguy

Reputation: 306

Check annotation on a variable in kotlin data class

I have to check if a particular variable inside a kotlin data class has an annotation present or not.

Annotation class

annotation class Test(
    val identifier: String
)

Data class

data class Player(
    val name: String,
    @property:Test("stance")
    val stance: String,
    @property:Test("check")
    val check: String
)

I have to check if a particular variable inside this player object has the Test annotation present or not.

fun execute(player: Player) {

   //while this works, but i have to check for a specific variable
    player::class.members.forEach{
        val testAnnotation = it.findAnnotation<Test>()
        if(testAnnotation != null) {
            // DO something
        }
    }


I need to do something like
      player.check.hasAnnotation<Test>()

}

Would appreciate any help here, TIA

Upvotes: 0

Views: 2231

Answers (1)

IR42
IR42

Reputation: 9682

You should use :: operator to create a member reference

player::check.hasAnnotation<Test>()

https://kotlinlang.org/docs/reflection.html#property-references

Upvotes: 1

Related Questions