How to create an instance of type T at runtime with TypeTags

前端 未结 4 429
梦如初夏
梦如初夏 2020-12-24 09:14

Here below is how to create a new instance of type T at runtime with Manifest:

trait MyTrait
class MyClass1(val name: String) extends MyTrait
cl         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 10:01

    Eventually here is the implementation that actually works - please just assume this answer comes from som-snytt:

    import scala.reflect.runtime._
    import scala.reflect.runtime.universe._
    
    class Test[T <: MyTrait : TypeTag] {
    
      def createInstance(args: AnyRef*)(ctor: Int = 0): T = {
        val tt = typeTag[T]
    
        currentMirror.reflectClass(tt.tpe.typeSymbol.asClass).reflectConstructor(
          tt.tpe.members.filter(m =>
            m.isMethod && m.asMethod.isConstructor
          ).iterator.toSeq(ctor).asMethod
        )(args: _*).asInstanceOf[T]
      }   
    }
    

    I hope that helps.

提交回复
热议问题