Created
October 16, 2013 03:01
-
-
Save passichenko/7002013 to your computer and use it in GitHub Desktop.
case class instantiation from class name via reflection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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