Create a method that receives a type parameter but not as a parameter, just like classOf

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]

Answers


Using Manifests:

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]()

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?


Need Your Help

How to use JGit to push changes to remote with OAuth access token

java jgit

I am able to push to remote with this piece of code

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.