Created
May 4, 2013 07:05
-
-
Save anonymous/5516563 to your computer and use it in GitHub Desktop.
Foo Factory
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
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