Accesing companion object from generic reified function


#1

I wanted to generalize a function loading entities from database, I’ve placed table name and array of fields in a companion object, and set up an interface to access those values.
Everything is Ok but for accessing those values in the generic function I could not find better than to create an instance of the object, and well it feels unnatural to me, how can I access the companion properties without instancing and Object?
Thank you

interface   MI{
    abstract val tName:String
    abstract val tSelect:Array<String>

}

data class KLevel( var id: Long =0,var nLocal:Int=0,var nServer:Int=0, var desc: String = ""):MI{
    override val tSelect:Array<String> get() =  tSelect
    override val tName:String    get() = tName
    companion object {
       const val tName : String = "KLEVEL"
       val tSelect: Array<String> = arrayOf("ID","NLOCAL","NSERVER","DESC")
   }
}

fun loadAll(): List<KLevel> {
    val L2: =  DB2.use { select(KLevel.tName,*KLevel.tSelect).exec { parseList(classParser<KLevel>()) } } }
    return L2
}


inline fun< reified T:MI  > loadAll():List<T>{
       val s=T::class.java.newInstance()    <---- Sure there is a better way
       val L2=DB2.use { select(s.tName, *s.tSelect).exec { parseList(classParser<T>()) }
    return L2
}

#2

The way I would solve this would be like this:

interface MI<T> {
    val tName: String
    val tSelect: Array<String>
    fun construct(args: Array<Any?>) : T
}

data class KLevel(var id: Long = 0, ...) {
    companion object Description: MI<KLevel> {
        const val tName : String = "KLEVEL"
        val tSelect: Array<Stirng> = ...
    }
}

fun <T> construct(description: MI<T>, args: Array<Any?>) : T {
    return description.construct(args)
}

You would just need to add a constructor mapping each element in args to the right field.
This could probably be done using the Annotation Processor. But than I don’t now DB2 so maybe this will give you everything you need already.

Just as a sidenote: calling construct(KLevel.Description, args) wont work. For some reason you need to pass the type argument construct<KLevel>(KLevel.Description, args).