Instantiate a class with Scala Macro or reflection

非 Y 不嫁゛ 提交于 2019-12-04 05:03:08

With a macro:

import scala.language.experimental.macros
import scala.reflect.macros.Context

object MacroExample {
  def newInstance[A <: Foo]: A with Bar = macro newInstance_impl[A]

  def newInstance_impl[A <: Foo](c: Context)(implicit A: c.WeakTypeTag[A]) = {
    import c.universe._

    c.Expr[A with Bar](q"new $A with Bar")
  }
}

This will work as expected, and will fail at compile time if you try to instantiate a class that doesn't have a no-argument constructor.

I've used quasiquotes here for the sake of clarity, but you could build the tree manually with a little more work. There's not really any good reason to, though, now that quasiquotes are available as a plugin for Scala 2.10.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!