Instantiating Object from String at Runtime in Scala

import scala.reflect.runtime.{universe => ru}
import scala.reflect.runtime.universe._

case class Person(name: String)

object ReflectionPoc {
	def main(args: Array[String]) { 
		val m = ru.runtimeMirror(getClass.getClassLoader)
		val p_clz = Class.forName("Person")
		val personClassSymbol = m.classSymbol(p_clz)
		val p = m.reflectClass(personClassSymbol)
		val p_Type = personClassSymbol.toType
		val p_ctor = p_Type.declaration(ru.nme.CONSTRUCTOR).asMethod
		val p_ctorm = p.reflectConstructor(p_ctor)
		val p_obj = p_ctorm("Mike")

Reflection Overview (Scala Docs)
Scala 2.10 Runtime Reflection from a Class Name (Veeb’s Brain Dump)
Symbols, Trees, and Types (Scala Docs)
Environment, Universes, and Mirrors (Scala Docs)
How to get constructor argument names using Scala-Macros

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>