【问题标题】:How to override toString of Object whose class defintion is not accessible?如何覆盖其类定义不可访问的对象的toString?
【发布时间】:2017-09-20 10:22:11
【问题描述】:

如果问题的主题令人困惑,请原谅我[请编辑主题]。

我很难理解/实现这个非常明显的用例。我敢肯定,肯定有一个我想不出的简单解决方案。

我的代码:

Response response = driver.execute("findElement", "{using=xpath, value=//*[@id='myID']}");

System.out.println(response.toString());

现在这个System.out.println 打印出来了:

(Response: SessionID: ffcebc9226c9671e7f6725a3b1f5a96c, Status: 0, Value: [org.openqa.selenium.remote.RemoteWebElement@c6bdd2e4 -> unknown locator])

由于已知原因,它没有正确打印完整的对象。因此, 我想@Override toString Response 类的方法。

现在我的困难是,如果我 extends Response 类如 CommandResponse 然后使用 CommandResponse 的类型转换如下:

CommandResponse response = (CommandResponse) driver.execute("findElement", "{using=xpath, value=//*[@id='myID']}");

我得到错误:

java.lang.ClassCastException: org.openqa.selenium.remote.Response 不能转换为 src.main.CommandResponse

所以,我的问题是,如何正确覆盖?

请指教。

【问题讨论】:

  • 覆盖它的原因是什么?为什么直接使用 driver.execute?
  • @TarunLalwani:我实际上是在 DB 中记录 Command、CommandParam、CommandResponse,然后尝试使用它们重播。这是根据我的用例要求。

标签: java selenium overriding tostring


【解决方案1】:

一个合适的解决方案是通过构造函数参数化将 Selenium Response 对象注入到您的包装器对象中。

然后构造函数将简单地为您传递的对象分配一个自己的Response 字段。

类似:

CommandResponse response = new CommandResponse(driver.execute(...));

...

public CommandResponse(Response arg) {
    this.response = arg;
}

这样,你就使用了一个包装对象和的组合。

您的CommandResponse 对象将覆盖toString 方法并通过从Response 对象中选择您需要的任何字段来构建String 表示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-19
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多