2016-10-01 64 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

是的,在我心中它是倒退是暫時的,只是簡單的回答不擔心。 –