As part of a rewriting mechanism, I need to obtain and execute a collection constructor of the same type as a given instance. The code below summarizes my attempt.
import scala.reflect.runtime.universe.TypeTag
def getEmptyCollection[N : TypeTag](collection: N): N = {
val runtime = scala.reflect.runtime.universe
val mirror = runtime.runtimeMirror(getClass.getClassLoader)
val classSymbol = runtime.typeOf[N].typeSymbol.asClass
val classMirror = mirror.reflectClass(classSymbol)
val constructorSymbol = runtime.typeOf[N].decl(runtime.termNames.CONSTRUCTOR).asMethod
val constructorMirror = classMirror.reflectConstructor(constructorSymbol)
constructorMirror()
}
val emptyList: List[Int] = getEmptyCollection(List(1, 2, 3))
This code, though, produces an instantiation exception: java.lang.InstantiationException was thrown
Perhaps "typeOf[N]" is the problem, but I'm just guessing. Would you know what the problem might be?
Thank you!
Aucun commentaire:
Enregistrer un commentaire