很抱歉提出这个问题,我已经看到有人提出过很多问题,但我的想法不是这样。
我的目标是制作一个重试函数,该函数将循环'n'的时间来尝试运行我作为参数传递的方法。
因此,在这种情况下,我想运行函数“ myFunction()”,但我知道有时返回的值为false,并且我想一直运行直到返回值为true。
这就是我希望它运行的方式:
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;
}
我知道这是不可能的(至少在Java 7中或在8中)
我已经看到了一些建议为特定函数创建对象的答案等...但这不会使重试函数通用,因为我需要为我想重试的每个方法重新创建一个对象,而这不是什么我想。
所以我想知道是否有一种“干净的”方法(即使在Java 8中也是如此)?
谢谢
您可以reflection
在这里尝试:
例如:
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句