1

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?

Saneen K P
  • 303
  • 1
  • 8
  • I think this could help https://stackoverflow.com/questions/20362493/how-to-get-annotation-class-name-attribute-values-using-reflection – Pavel Jan 03 '23 at 14:07
  • @Pavel no thats not helping , its outputing some weird values. I guess it is for normal java class . Mine is for kotlin data class. – Saneen K P Jan 03 '23 at 14:40

1 Answers1

0

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]
Karsten Gabriel
  • 3,115
  • 6
  • 19