2016-10-01 66 views
5

说,我有一个注释类科特林:科特林 - 如何获得注释的属性值

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

我怎样才能得到name属性从@Table注释的价值?

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

回答

7

你可以简单:

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

请注意,我用的是is操作,因为注解有RUNTIME保留,因此它是集合中的Table注释的实际情况。但对于任何注释了以下工作:

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

'find'相当于firstOrNull'的','不first' – Ilya

+0

是的,在我心中它是倒退是暂时的,只是简单的回答不担心。 –