【发布时间】:2020-07-20 19:05:00
【问题描述】:
我有这样的注释:
@Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class Foo(val bar: Int)
使用一些反射,我读到了这样的注释:
for (prop in myClass.memberProperties) {
val foo = prop.findAnnotation<Foo>() ?: continue
// Do something with foo
}
当类被定义为这样时,这很好用
class MyClass {
@Foo(bar = 1)
var myProp: Int = 0
}
// prop.findAnnotation<Foo>() => { bar: 1 }
但是当类被定义为像 data 类并且在构造函数中具有属性时,注释的目标是 VALUE_PARAMETER,我无法在我的 memberProperties 上得到它:
data class MyOtherClass (
@Foo(bar = 1)
val myProp: Int
)
// prop.findAnnotation<Foo>() => null
我当然可以用@property:Foo(bar = 1) 明确地定位它,但我想使用它而不用担心这个,就像jackson 中的@JsonProperty 一样。
在搜索注释时,我当然可以检查 memberProperties 以及构造函数中的参数......但是 KParameter 和 KProperty 只有 KAnnotated 作为共同的父级,这使得两者一起工作有点困难可以互换,因为我还需要属性的类型和名称,而不仅仅是注释。
这是更好的方法吗?
【问题讨论】:
标签: kotlin reflection annotations jvm