-
-
Save jroesch/5516565 to your computer and use it in GitHub Desktop.
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[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