有没有一种方法可以在同一方法中传递不同(但特定)类型的对象,并根据对象的类型采用不同的处理方式
Is there a way to pass different (but specific) types of objects in same method and have different ways to handle based on the type of object
我必须编写一个方法来点击网页上的元素。
问题是我的方法 中只能 两种类型的对象中的任何一种,即 'WebElement' 对象或 'By' 对象。因此,为了做到这一点,我必须为两个重载方法编写重复的代码行,如下所示:
public void clickElement(WebElement element) {
Line 1;
Line 2;
element.click();
Line 3;
}
public void clickElement(By locator) {
Line 1;
Line 2;
driver.findElement(locator).click();
Line 3;
}
是否可以只编写一种方法,该方法只能采用两种类型的对象中的一种并相应地运行? 像这样:
public void clickElement(WebElement element **OR** By locator) {
Line 1;
Line 2;
element.click; **OR** driver.findElement(locator).click();
Line 3;
}
Let me know if my question needs more clarification or inputs.
看看 java 泛型,特别是泛型方法 - https://docs.oracle.com/javase/tutorial/extra/generics/methods.html
我没有使用硒。根据您的代码,我假设 driver.findElement()
returns WebElement
,并且第 1、2、3 行在两种方法中完全相同。如果是这种情况,我能想到的最好的实现方式如下。
public void clickElement(WebElement element) {
Line 1;
Line 2;
element.click();
Line 3;
}
public void clickElement(By locator) {
clickElement(driver.findElement(locator));
}
通过这样做,我们可以最大限度地重用代码,同时保留强制执行可以传递给这些方法的 class 类型的方法签名。
我必须编写一个方法来点击网页上的元素。 问题是我的方法 中只能 两种类型的对象中的任何一种,即 'WebElement' 对象或 'By' 对象。因此,为了做到这一点,我必须为两个重载方法编写重复的代码行,如下所示:
public void clickElement(WebElement element) {
Line 1;
Line 2;
element.click();
Line 3;
}
public void clickElement(By locator) {
Line 1;
Line 2;
driver.findElement(locator).click();
Line 3;
}
是否可以只编写一种方法,该方法只能采用两种类型的对象中的一种并相应地运行? 像这样:
public void clickElement(WebElement element **OR** By locator) {
Line 1;
Line 2;
element.click; **OR** driver.findElement(locator).click();
Line 3;
}
Let me know if my question needs more clarification or inputs.
看看 java 泛型,特别是泛型方法 - https://docs.oracle.com/javase/tutorial/extra/generics/methods.html
我没有使用硒。根据您的代码,我假设 driver.findElement()
returns WebElement
,并且第 1、2、3 行在两种方法中完全相同。如果是这种情况,我能想到的最好的实现方式如下。
public void clickElement(WebElement element) {
Line 1;
Line 2;
element.click();
Line 3;
}
public void clickElement(By locator) {
clickElement(driver.findElement(locator));
}
通过这样做,我们可以最大限度地重用代码,同时保留强制执行可以传递给这些方法的 class 类型的方法签名。