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
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
}