Skip to content

Instantly share code, notes, and snippets.

@passichenko
Created October 16, 2013 03:01
Show Gist options
  • Select an option

  • Save passichenko/7002013 to your computer and use it in GitHub Desktop.

Select an option

Save passichenko/7002013 to your computer and use it in GitHub Desktop.
case class instantiation from class name via reflection
package test
object TestScala extends App {
val className = "test.MyClass"
val value = "test"
import scala.reflect.runtime.{universe => ru}
val mirror = ru.runtimeMirror(getClass.getClassLoader)
val classSymbol = mirror.staticClass(className)
val classMirror = mirror.reflectClass(classSymbol)
val constructorSymbol = classSymbol.toType.declaration(ru.nme.CONSTRUCTOR).asMethod
val constructorMirror = classMirror.reflectConstructor(constructorSymbol)
val c = constructorMirror(value)
println(c)
}
case class MyClass(value: String)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment