如何在java中将函数作为参数传递以多次运行
很抱歉问这个问题,我已经看到有人问了很多问题,但不是我想的那样 我的目标是创建一个重试函数,该函数将循环“n”个时间来尝试运行我作为参数传递的方法 因此,在本例中,我希望运行函数“myFunction()”,但我知道有时返回值为false,我希望运行它直到返回值为true 这就是我希望它运行的方式:如何在java中将函数作为参数传递以多次运行,java,Java,很抱歉问这个问题,我已经看到有人问了很多问题,但不是我想的那样 我的目标是创建一个重试函数,该函数将循环“n”个时间来尝试运行我作为参数传递的方法 因此,在本例中,我希望运行函数“myFunction()”,但我知道有时返回值为false,我希望运行它直到返回值为true 这就是我希望它运行的方式: public static void main (String [] args){ boolean did work = retry (myFunction(),5) if(didw
public static void main (String [] args){
boolean did work = retry (myFunction(),5)
if(didwork){
System.out.println("I found my stuff");
} else {
System.out.println("I didn't found my stuff");
}
}
public boolean retry (Function function, int loopTry){
boolean success = false;
for(int i=0 ; i<loopTry ; i++){
success = function.run();
if(success){
break;
}
}
return success;
}
public boolean myFunction(){
boolean found = false;
//do stuff
if(stuff){
found = true;
}
return found;
}
publicstaticvoidmain(字符串[]args){
布尔值did work=重试(myFunction(),5)
如果(干活儿){
System.out.println(“我找到了我的东西”);
}否则{
System.out.println(“我没有找到我的东西”);
}
}
公共布尔重试(函数,int-loopTry){
布尔成功=假;
对于(int i=0;i,您可以向myFunction()添加一个while循环,该循环用于“重试”在函数内部。这将只是一个附加行。如果将最大尝试次数定义为n,则最多两行或三行。在第二种情况下,您已经重新创建了尝试直到得到true或达到尝试次数的效果。您可以在此处尝试反射
:
例如:
publicstaticvoidmain(字符串[]args)抛出NoSuchMethodException、SecurityException、IllegalAccessException、,
IllegalArgumentException,InvocationTargetException{
方法方法=Test.class.getMethod(“myFunction”);
布尔didwork=重试(方法5);
如果(干活儿){
System.out.println(“我找到了我的东西”);
}否则{
System.out.println(“我没有找到我的东西”);
}
}
公共静态布尔重试(Method,int-loopTry)
抛出IllegalAccessException、IllegalArgumentException、InvocationTargetException{
布尔成功=假;
for(int i=0;i
用myFunction创建一个接口。然后用你想要的东西实现一个类。你需要将这个类的一个实例传递给retry
来调用这个函数。你的函数似乎没有输入,也没有输出。看看Java 8中的Supplier
接口。retry
接受函数ion
对象参数,而不是布尔值
。此代码是否编译?对于Java 8,请查看lambdas和函数接口。对于Java 8之前的版本,请查看反射。在Java 8中,您说的是重试(this::myFunction)
。问题是我不想只做一个循环,我想在每次尝试之间进行多次尝试&我想使用此重试函数进行多次尝试。我只是想知道是否可以通过创建此“重试”来避免在每个函数中都有多个循环函数感谢您的回答,它非常接近工作状态。我必须使它们不是静态的,并给出一个对象实例(在本例中为测试)作为参数来调用,它确实工作了
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Method method = Test.class.getMethod("myFunction");
boolean didwork = retry(method, 5);
if (didwork) {
System.out.println("I found my stuff");
} else {
System.out.println("I didn't found my stuff");
}
}
public static boolean retry(Method method, int loopTry)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
boolean success = false;
for (int i = 0; i < loopTry; i++) {
success = (Boolean) method.invoke(null);
if (success) {
break;
}
}
return success;
}
public static boolean myFunction() {
boolean found = false;
//do stuff
if(stuff){
found = true;
}
return found;
}