如何在运行时使用Scala的清单类实例化已擦除的类? [英] How can I use Scala's Manifest class to instantiate the erased class at runtime?

查看:105
本文介绍了如何在运行时使用Scala的清单类实例化已擦除的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些WebDriver + PageObject的事情.

(如果您不熟悉PageObjects,则这是一种模式,其中您有一个类代表您站点上的每个页面,该类使用域语言公开了页面的所有功能,并在测试中隐藏了HTML内容.)

我想变得懒惰,并且在我的所有其他Pages继承自的抽象Page类中,有一个提交"方法.我还希望该方法重新创建下一个Page子类并返回它.

这是我在Page类中的内容:

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]
}

这就是我的称呼方式:

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

对此进行编译,我得到:

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

我以为我很聪明,但显然我并不聪明. ;) 我在做什么错了?

解决方案

您需要使Manifest与类型参数相关,即

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

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?

解决方案

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

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

这篇关于如何在运行时使用Scala的清单类实例化已擦除的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆