gpt4 book ai didi

java - 有什么方法可以在java中传递带有2个输入参数的函数吗?

转载 作者:行者123 更新时间:2023-11-30 03:28:40 24 4
gpt4 key购买 nike

我怎样才能在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”等等?

另一个选择是定义一个新类,它结合了您必须传递的两个/三个/...参数。

关于java - 有什么方法可以在java中传递带有2个输入参数的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29599864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com