【发布时间】:2017-04-12 14:41:16
【问题描述】:
我正在做一个小方法,我需要传递一个方法作为参数,所以我不必重复代码。 所以我必须使用这个方法,唯一改变的是我在这个方法中使用的方法。因此,如果我可以在参数中传递一个方法,它将大大简化我的代码。 这是我的代码。我可以使用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;
}
【问题讨论】:
-
你要传递的所有方法都具有相同的签名吗?这是什么?
-
我有 4 或 5 种方法。两种用于在链表上推送和弹出的方法,另外两种用于相同但在可调整大小的数组上的方法
-
我真的不明白你在做什么。我认为您的方法是错误的,并且有更好的方法。你能解释一下为什么需要把它作为参数吗?因为您将使用参数 n 次调用您的方法,所以您可以只调用您的方法,这将是同样的努力
-
我有一个巨大的方法代码可以在 excel 中写入一些 tsts 数据。我正在链表和可调整大小的数组中进行推送和弹出操作,所以现在我必须重复此代码 2 次,一次用于链表测试,另一次用于可调整大小的测试。如果我可以传递计算推送和弹出的方法,我可以只使用一种方法,该方法将写入 excel 我想作为参数传递的方法的输出
标签: java methods parameters