say, i have one Kotlin class with annotations:

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

如何从@Table annotation获取name属性的值?

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)

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相关问答推荐

Kotlin 海峡没有结束

新的jOOQ Gradle插件无法正确处理自引用关系

S使用MAP和ElseThrow的习惯用法是什么?

如何在 kotlin 中的数据类中为变量提供多种类型

如何从 Period.between() 返回的字符串中提取信息? (Kotlin )

Kotlin中用于调用常量名称的枚举类方法之间的区别

Kotlin Path.useLines { } - 如何不获取 IOException("Stream closed")?

Kotlin:伴随对象内的函数扩展

有没有办法在spring webflux和spring data react中实现分页

Kotlin 有 array.indexOf 但我无法弄清楚如何做 array.indexOfBy { lambda }

如何在 kotlin 中生成 json 对象?

从命令行运行Java到Kotlin转换器?

kotlin 委托有什么用?

IllegalStateException:function = , count = 3, index = 3

uses-sdk:minSdkVersion 16 不能小于库中声明的版本 23

使用 kotlin 每 3 位数添加逗号或点

Failure delivering result on activity result

Kotlin内联属性的用例是什么?

Kotlin - 如何获取注释属性值

是否可以在不使用class的情况下将 Mockito 与 Kotlin 一起使用?