我正在做一个小方法,我需要传递一个方法作为参数,所以我不必重复代码。 所以我必须使用这个方法,唯一改变的是我在这个方法中使用的方法。因此,如果我可以在参数中传递一个方法,它将大大简化我的代码。 这是我的代码。我可以使用java的refletct吗?
public static void testsForLinkedLists(int potencia,
int repeticoesteste, int somarAoArray, String ficheiroExcel,
int validararray, Method pushMethod)
我有这两种方法,我想将其用作参数
public class measuring_tests {
public static double timeToPushLinkedStack(int intendedPushes) {
final LinkedStackOfStrings measuringTimeToPush = new LinkedStackOfStrings();
final String element = "measuring_test";
int numberOfPushesDone = 0;
double totalPushTime = 0;
Stopwatch stopwatch = new Stopwatch();
while (numberOfPushesDone < intendedPushes) {
measuringTimeToPush.push(element);
numberOfPushesDone++;
}
totalPushTime = stopwatch.elapsedTime();
while (measuringTimeToPush.size > 0) {
measuringTimeToPush.pop();
}
return totalPushTime;
}
public static double timeToPopLinkedStack(int intendedPops) {
final LinkedStackOfStrings measuringTimeToPop = new LinkedStackOfStrings();
final String element = "measuring_test";
while (measuringTimeToPop.size < intendedPops) {
measuringTimeToPop.push(element);
}
double totalPopTime = 0;
Stopwatch stopwatch = new Stopwatch();
while (measuringTimeToPop.size > 0) {
measuringTimeToPop.pop();
}
totalPopTime = stopwatch.elapsedTime();
return totalPopTime;
}
最佳答案
如果所有方法都具有相同的签名 double m(int)
,那么您可以使用类似 the IntToDoubleFunction
interface 的内容。并传递方法引用:
public static void testsForLinkedLists(int potencia,
int repeticoesteste, int somarAoArray, String ficheiroExcel,
int validararray, IntToDoubleFunction pushMethod)
你可以这样调用它:
testsForLinkedLists(...., measuring_tests::timeToPushLinkedStack);
关于java - java中将方法作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43372745/