gpt4 book ai didi

kotlin - Kotlin通过反射读取属性注释

转载 作者:行者123 更新时间:2023-12-02 13:12:08 24 4
gpt4 key购买 nike

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

为什么注释不可用?

@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->否

最佳答案

您可以将其指定为@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}") }
}
输出:

Is MyAnnotation annotated - true

Annotation present is - packageName.MyAnnotation

关于kotlin - Kotlin通过反射读取属性注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59527696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com