我正在做一个小方法,我需要传递一个方法作为参数,所以我不需要重复代码。所以我必须使用这个方法,唯一改变的是我在这个方法中使用的方法。因此,如果我可以在参数中传递一个方法,它将简化我的代码。这是我的代码。我可以使用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;
}发布于 2017-04-12 23:00:13
如果所有的方法都有相同的签名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);发布于 2017-04-12 23:14:09
好的。我明白了:)试着看一下本教程:https://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html也可以通过以下方式获取方法: fooMethod = MyObject.class.getMethod("foo")
https://stackoverflow.com/questions/43372745
复制相似问题