lundi 14 mai 2018

How to create generic parameter type object at runtime [duplicate]

This question is an exact duplicate of:

I need to create the object of type T inside my class. The problem is that I can only use reified in an inline function (inside class) and cannot pass T to it. so how do I fix this i.e. what createObjectT() would be like?

class EndPoint<T>{

  fun doSomething(){
    val obj = createObjectT()
    ...
  }
}

I tried creating the following as a member function but I was unable to call it using the T type.

  inline fun<reified T>create(): T{
        var ret: T? = null
        val clazz = T::class

        label@
        for(item in clazz.constructors){
            if(item.parameters.isEmpty()){
                ret = item.call()
                break@label
            }
        }
        return ret!!
    }

because it complains at this line

val obj = create<T>()   // error, use a class type





Aucun commentaire:

Enregistrer un commentaire