JoseHdez_2
JoseHdez_2

Reputation: 4161

In Kotlin, restrict annotation target based on the type of the property

In Kotlin, as in Java, we can restrict the annotation to only be used in specific kinds of elements, with the @Target meta-annotation (ex. @Target(AnnotationTarget.VALUE_PARAMETER) so the annotation can only be applied to value parameters).

My use case is that I want to validate properties using reflection (ex. @MustNotBeEmpty name: String), and I'd like to restrict the kinds of annotations based on the type of property (ex. @MustBePositive number: Int can only be applied to "Int" properties). Comments about the feasibility of reflection-based validation are welcome as well.

Is there any way that this can be achieved in compilation time, or will I need to check this in runtime?

Upvotes: 4

Views: 1588

Answers (1)

Michael Piefel
Michael Piefel

Reputation: 19968

There is nothing in the annotation framework that allows this. kotlin.annotation.AnnotationTarget has a wide range of allowed values and can restrict the placement of annotations quite fine-grained (such as ‘only on the getter’), but it’s an closed enum. There is no annotation annotating annotations that takes any type parameter.

All you can do is write a compiler-plugin that performs these checks manually at compile time.

Upvotes: 4

Related Questions