Skip to content

Instantly share code, notes, and snippets.

Created May 4, 2013 07:05
Show Gist options
  • Save anonymous/5516563 to your computer and use it in GitHub Desktop.
Save anonymous/5516563 to your computer and use it in GitHub Desktop.
Foo Factory
abstract class Foo(x: Int)
class Bar(x: Int) extends Foo(x)
class Baz(x: Int) extends Foo(x)
object Foo {
import scala.reflect.runtime.{ universe => ru }
def create[A <: Foo](x: Int)(implicit tt: TypeTag[A]): A = {
val mirror = ru.runtimeMirror(getClass.getClassLoader)
val aClass = ru.typeOf[A].typeSymbol.asClass
val cm = mirror.classMirror(aClass)
val aCtor = ru.typeOf[A].declaration(ru.nme.CONSTRUCTOR).asMethod
val ctor = cm.reflectConstructor(aCtor)
ctor(x)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment