首页 > 解决方案 > Kotlin 通过反射读取属性注解

问题描述

我已经为属性创建了一个注释,现在我想在运行时通过反射来读取它。在我看来,我做的一切都是正确的,但没有注释。

为什么注释不可用?

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER)
annotation class MyAnnotation

class MyClass(@MyAnnotation val attr: List<String>)

fun main(args: Array<String>) {
    var prop = MyClass::attr
    prop.annotations.forEach { println("prop.annotations -> " + it) }
    prop.javaClass.getAnnotations().forEach { println("prop.javaClass.getAnnotations -> " + it) }
    println("isAnnotationPresent -> ${prop.javaClass.isAnnotationPresent(MyAnnotation::class.java)}")
}

输出:
prop.javaClass.getAnnotations -> @kotlin.Metadata(xi=0, bv=[1, 0, 3], mv=[1, 1, 16], k=3, xs=, d1=[], d2=[], pn=) isAnnotationPresent -> false

标签: kotlinreflectionpropertiesannotations

解决方案


@Target(AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER)您可以将其指定为@Target(AnnotationTarget.FIELD)并按如下方式访问它,而不是将注释目标指定为:

@Target(AnnotationTarget.FIELD)
annotation class MyAnnotation

class MyClass(@MyAnnotation val attr: String)

fun main(args: Array<String>) {
    val prop = MyClass::attr
    println("Is MyAnnotation annotated - ${prop.javaField?.isAnnotationPresent(MyAnnotation::class.java)}")
    prop.javaField?.annotations?.forEach { println("Annotation present is - ${it.annotationClass.qualifiedName}") }
}

输出:

MyAnnotation 是否已注释 - 是的

存在的注释是 - packageName.MyAnnotation


推荐阅读