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

前端 未结 4 413
梦如初夏
梦如初夏 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 09:55

    j3d,

    I believe the manifest approach is deprecated. You can use scala code below to create an instance via reflection. You will have to adjust the code slightly to factor for classes with multiple constructors, and/or arguments

    Code is based on http://docs.scala-lang.org/overviews/reflection/overview.html

    import scala.reflect.runtime.{universe => ru}
    import ru._
    
    ...
    
    class Person { }
    
    
    def example() = 
    {
       val instance1 = createInstance[Person]()
       val instance2 = createInstance(typeOf[Person])
    }
    
    
    def createInstance[T:TypeTag]() : Any= {
        createInstance(typeOf[T])
    }
    
    
    def createInstance(tpe:Type): Any = {
        val mirror = ru.runtimeMirror(getClass.getClassLoader)
        val clsSym = tpe.typeSymbol.asClass
        val clsMirror = mirror.reflectClass(clsSym)
        val ctorSym = tpe.decl(ru.termNames.CONSTRUCTOR).asMethod
        val ctorMirror = clsMirror.reflectConstructor(ctorSym)
        val instance = ctorMirror()
        return instance
    }
    

提交回复
热议问题