kotlin - 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
解决方案
@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
推荐阅读
- php - PHP 部署到 Linux 和 Windows
- php - 事件日历 - 更改列表视图的标题
- .net - 为什么我的 JWT 令牌/断言从 Einstein OAuth 服务收到“无效令牌”响应?
- encoding - 无法从两个不同的来源获得相同的 base 64 模数
- c++ - 单击 QTableWidget 中的 QComboBox
- c# - TransformBlock 中 InputQueue 的每个元素
每当读取记录时被覆盖 - angularfire - 使用角火的谷歌身份验证
- python - 从 URL 获取到所有 Flask 路由的变量
- angular - 尝试从本地存储中检索数据时出现问题
- react-native - 是否可以在本机反应中创建交易图(如照片中)?