gpt4 book ai didi

java - 是否有解决方案可以通过方法引用使方法调用函数具有动态数量的参数?

转载 作者:行者123 更新时间:2023-12-01 16:49:32 25 4
gpt4 key购买 nike

所以,我有以下类(class):

public class MainClass{

public void run(String infoOne, String infoTwo, String infoThree, String infoFour, String infoFive, String infoSix){
SomeClass someClass = new SomeClass();
someClass.runSomeMethod();
someClass.runSomeMethodTwo( infoOne);
someClass.runSomeMethodThree( infoThree, infoOne, infoSix);
someClass.runSomeMethodFour( infoTwo, infoFive);
someClass.runSomeMethodFive(infoThree, infoFive, infoOne, infoSix);
}
}

‌‌

public class SomeClass{
public boolean runSomeMethod(){
// do something
}

public boolean runSomeMethodTwo(String arg){
// do something
}

public boolean runSomeMethodThree(String argOne, String argTwo, String argThree){
// do something
}

public boolean runSomeMethodFour(String argOne, String argTwo){
// do something
}

public boolean runSomeMethodFive(String argOne, String argTwo, String argThree, String argFour){
// do something
}
}

正如您所看到的,这是一堆仅采用字符串作为参数的方法(但每次的数量不同)。我现在想要的是将每个方法包装在 try catch block 中并记录一些结果。为此,我想在两者之间放置一个处理日志记录的方法:

log(SomeClass::runSomeMethodFour);

public void log(????? method, String...args){
try{
if(method.execute(args);
System.out.println("Success!");
} else {
System.out.println("Failed to execute!");
}
} catch (Exception e){
e.printStackTrace();
}
}

这在某种程度上是可能的吗?将动态数量的参数传递给 lambda 函数?或者我可以用泛型做点什么吗?

最佳答案

无需创建复杂的基于反射的解决方案。您的问题源于不必要的尝试来分离方法和参数参数,而不是仅仅封装整个操作,如

public class MainClass {
public void run(String infoOne, String infoTwo, String infoThree,
String infoFour, String infoFive, String infoSix) {
SomeClass someClass = new SomeClass();
log(() -> someClass.runSomeMethod());
log(() -> someClass.runSomeMethodTwo(infoOne));
log(() -> someClass.runSomeMethodThree(infoThree, infoOne, infoSix));
log(() -> someClass.runSomeMethodFour(infoTwo, infoFive));
log(() -> someClass.runSomeMethodFive(infoThree, infoFive, infoOne, infoSix));
}
public void log(BooleanSupplier method) {
try {
if(method.getAsBoolean()) {
System.out.println("Success!");
} else {
System.out.println("Failed to execute!");
}
} catch (Exception e ){
e.printStackTrace();
}
}
}

感谢 log 的工作方法,只有boolean返回值是相关的,它与 BooleanSupplier 的功能签名匹配.

关于java - 是否有解决方案可以通过方法引用使方法调用函数具有动态数量的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43292477/

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