创建一个接收类型参数但不作为参数的方法,就像 classOf 一样
我有以下代码:
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]
I have the following code:
class ServletSpec extends Specification {
def createServlet[T <: HttpServlet](clazz: Class[T]): T = {
val instance = clazz.newInstance()
instance.init()
instance
}
}
That is called like this:
spec.createServlet( classOf[DocumentationServlet] )
How can I define this method so that I can call it like this:
spec.createServlet[DocumentationServlet]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用Manifests:
隐式参数由编译器填充,Manifest 包含创建新实例所需的类型信息。有关详细信息,请参阅什么是在 Scala 中清单以及何时需要它?
Using Manifests:
The implicit parameter is filled in by the compiler, and a Manifest contains the type information required to create a new instance. For more information, see What is a Manifest in Scala and when do you need it?