创建一个接收类型参数但不作为参数的方法,就像classOf一样

时间:2011-11-29 19:47:27

标签: scala reflection

我有以下代码:

class ServletSpec extends Specification {

    def createServlet[T <: HttpServlet](clazz: Class[T]): T = {

        val instance = clazz.newInstance()
        instance.init()

        instance

    }

} 

这就是这样称呼的:

spec.createServlet( classOf[DocumentationServlet] )

如何定义此方法以便我可以这样调用它:

spec.createServlet[DocumentationServlet]

1 个答案:

答案 0 :(得分:5)

使用清单:

class ServletSpec extends Specification {
    def createServlet[T <: HttpServlet]()(implicit manifest: Manifest[T]) = {
        val instance = manifest.erasure.newInstance().asInstanceOf[T]
        instance.init()

        instance
    }
}

new ServletSpec().createServlet[DocumentationServlet]()

隐式参数由编译器填充,Manifest包含创建新实例所需的类型信息。有关详细信息,请参阅What is a Manifest in Scala and when do you need it?