在 Kotlin 中,根据 属性 的类型限制注释目标

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

在 Kotlin 中,就像在 Java 中一样,我们可以限制注解仅用于特定种类的元素,使用 @Target 元注解(例如 @Target(AnnotationTarget.VALUE_PARAMETER) 所以注解只能应用于值参数)。

我的用例是我想使用反射来验证属性(例如 @MustNotBeEmpty name: String),并且我想根据 属性 的类型限制注释的种类(例如. @MustBePositive number: Int 只能应用于 "Int" 属性)。关于基于反射的验证的可行性的评论 are welcome as well

有什么方法可以在编译时实现,还是需要在运行时检查?

注释框架中没有任何内容允许这样做。 kotlin.annotation.AnnotationTarget 具有广泛的允许值,并且可以非常细粒度地​​限制注释的放置(例如“仅在 getter 上”),但它是一个封闭的枚举。没有annotation annotating annotations takes any type parameter.

您所能做的就是编写一个编译器插件,在编译时手动执行这些检查。