Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - how to get annotation attribute value

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?
}
like image 348
Ace.Yin Avatar asked Oct 01 '16 11:10

Ace.Yin


1 Answers

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
like image 163
4 revs Avatar answered Oct 18 '22 18:10

4 revs