Skip to content

Instantly share code, notes, and snippets.

@jroesch
Forked from anonymous/gist:5516563
Last active December 16, 2015 23:49
Show Gist options
  • Save jroesch/5516565 to your computer and use it in GitHub Desktop.
Save jroesch/5516565 to your computer and use it in GitHub Desktop.
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[Nothing >: A <: Foo](x: Int)(implicit tt: ru.TypeTag[A]): A = {
val mirror = ru.runtimeMirror(getClass.getClassLoader)
val aClass = ru.typeOf[A].typeSymbol.asClassval
val cm = mirror.reflectClass(aClass)
val aCtor = ru.typeOf[A].declaration(ru.nme.CONSTRUCTOR).asMethod
val ctor = cm.reflectConstructor(aCtor)
ctor(x).asInstanceOf[A]
}
}
class Baraz(x: Int) extends Bar(x)
Foo.create[Baraz](1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment