Get the annotation variable and its type of a data class

352 Views Asked by At

I have a data class in kotlin , which is also a Room entity. Eg :

data class Pack(

    @ColumnInfo(name = "name")
    @SerializedName("name")
    var name:String,

    @SerializedName("is_free")
    @ColumnInfo(name="is_free")
    var isFree:Boolean,

    @SerializedName("is_new")
    @ColumnInfo(name="is_new")
    var isNew:Boolean,

){ .. }

I want to get all the values of @ColumnInfo(name) , ie I want all the Room anotation names and its corresponding kotlin varible and its types. ie I want something like. Eg :

name - name - String is_free - isFree - Boolean is_new - isNew - Boolean

Is that possible using kotlin reflection of something?

1

There are 1 best solutions below

1
On

Yes, you can go through the parameters of the primary constructor of your data class, collect the annotations and print them out like this:

fun <T: Any> KClass<T>.getInfo(): List<String> = 
    primaryConstructor!!.parameters.map { it.getInfo() }

fun KParameter.getInfo(): String {
    val columnInfo = findAnnotation<ColumnInfo>()
    return "$name - ${columnInfo?.name} - $type"
}

Then calling Pack::class.getInfo() gives you the following:

[name - name - kotlin.String, isFree - is_free - kotlin.Boolean, isNew - is_new - kotlin.Boolean]