如何在 Java 中传递一个Function
类对象,该对象获得 2 个或更多参数?
我有这个代码:
public String getSrcAfterWait(final By by) {
String currentSrc;
try {
currentSrc = tryToGetSrc(by);
} catch (StaleElementReferenceException ex)
{
currentSrc = tryToGetSrc(by);
}
return currentSrc;
}
private String tryToGetSrc(By by) {
WebElement webElement = getElementAfterWaitForDisplay2(by);
String currentSrc = null;
if (webElement != null) {
currentSrc = webElement.getAttribute("src");
}
return currentSrc;
}
private String tryToGetText(final By by) {
String currentSrc = null;
WebElement webElement = getElementAfterWaitForDisplay2(by);
if (webElement != null) {
currentSrc = webElement.getText();
}
return currentSrc;
}
public String getButtonTextAfterWait(final By by) {
String currentText;
try {
currentText = tryToGetText(by);
} catch (StaleElementReferenceException ex)
{
currentText = tryToGetText(by);
}
return currentText;
}
我想这样概括一下:
public <T,V> V tryGetAttribute(final By by, Function<T,V> getFunc) {
WebElement webElement = getElementAfterWaitForDisplay2(by);
V answer = null;
if (webElement != null) {
try {
answer = getFunc.apply(webElement, getFunc);//
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return answer;
}
public String getButtonTextAfterWait(final By by) {
String currentText;
Function<WebElement, String> getFunc = webElement -> webElement.getText();
try {
currentText = tryGetAttribute(by, getFunc);
} catch (StaleElementReferenceException ex) {
currentText = tryGetAttribute(by, getFunc);
}
return currentText;
}
但我看不到任何方法可以传递带有 2 个输入参数的函数。
有没有办法或抽象效率不高?
至少在Java8中,有BiFunction
看:
https://docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html
如果你需要更多的参数;是什么阻止你简单地创建自己的"TripleFunction",等等?
另一种选择是定义一个新类,该类结合了两个/三个/...你必须通过的论点。