Kotlin - how to get annotation attribute value

亡梦爱人 提交于 2020-07-28 16:45:48

问题


say, i have one Kotlin class with annotations:

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

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?
}

回答1:


You can simply:

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

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


来源:https://stackoverflow.com/questions/39806025/kotlin-how-to-get-annotation-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!