Kotlin-如何获取注释属性值 [英] Kotlin - how to get annotation attribute value

查看:625
本文介绍了Kotlin-如何获取注释属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个带有注释的Kotlin类:

say, i have one Kotlin class with annotations:

@Entity @Table(name="user") data class User (val id:Long, val name:String)

如何从@Table批注中获取name属性的值?

How can i get the value of name attribute from @Table annotation?

fun <T> tableName(c: KClass<T>):String {
    // i can get the @Table annotation like this:
    val t = c.annotations.find { it.annotationClass == Table::class }
    // but how can i get the value of "name" attribute from t?
}

推荐答案

您可以简单地:

val table = c.annotations.find { it is Table } as? Table
println(table?.name)

注意,我使用了is运算符,因为注释具有RUNTIME保留,因此它是集合中Table注释的实际实例.但是以下内容适用于任何注释:

Note, I used the is operator since the annotation has RUNTIME retention and therefore it is an actual instance of the Table annotation within the collection. But the following works for any annotation:

val table = c.annotations.find { it.annotationClass == Table::class } as? Table

这篇关于Kotlin-如何获取注释属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆