How can I use Scala's Manifest class to instantiate the erased class at runtime?

寵の児 提交于 2019-12-23 16:33:04

问题


I'm doing some WebDriver+PageObject stuff.

(If your not familiar with PageObjects, this is a pattern where you have a class representing each page on your site which exposes all the functions of the page using the domain language, hiding the HTML stuff from the test.)

I want to be lazy and have one 'submit' method in my abstract Page class that all my other Pages extend from. I also want this method to new up the next Page subclass and return it.

Here is what I have in the Page class:

def submitExpecting[P <: Page[P]](implicit m: Manifest[_]): P = {
  driver.findElement(By.xpath("//input[@type='submit']")).click
  m.erasure.getConstructor(classOf[WebDriver]).newInstance(driver).asInstanceOf[P]
}

and here's how I'm calling it:

val userHomePage = userSignupPage
      .login("graham")
      .acceptTermsAndConditions
      .submitExpecting[UserHomePage]

Compiling this, I get:

error: could not find implicit value for parameter m: Manifest[_]
.submitExpecting[UserHomePage]

I thought I was being smart, but clearly I'm not. ;) What am I doing wrong?


回答1:


You need to make your Manifest be related to the type parameter, i.e.

def submitExpecting[P <: Page[P]](implicit m: Manifest[P]): P



回答2:


In addition to Ben's answer, you may want to consider using the Scala 2.8.x syntax:

def submitExpecting[P <: Page[P] : Manifest]: P

Afterwards, you can access the manifest via the manifest[P] construct. It feels a little cleaner overall (at least to me...)



来源:https://stackoverflow.com/questions/3890358/how-can-i-use-scalas-manifest-class-to-instantiate-the-erased-class-at-runtime

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