首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在java中将方法作为参数传递。

在java中将方法作为参数传递。
EN

Stack Overflow用户
提问于 2017-04-12 22:41:17
回答 2查看 429关注 0票数 1

我正在做一个小方法,我需要传递一个方法作为参数,所以我不需要重复代码。所以我必须使用这个方法,唯一改变的是我在这个方法中使用的方法。因此,如果我可以在参数中传递一个方法,它将简化我的代码。这是我的代码。我可以使用java的refletct吗?

代码语言:javascript
运行
复制
public static void testsForLinkedLists(int potencia,
            int repeticoesteste, int somarAoArray, String ficheiroExcel,
            int validararray, Method pushMethod)

我有这两个方法,我想用它作为参数

代码语言:javascript
运行
复制
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;
    }
EN

回答 2

Stack Overflow用户

发布于 2017-04-12 23:00:13

如果所有的方法都有相同的签名double m(int),那么你可以使用类似the IntToDoubleFunction interface的东西并传递一个方法引用:

代码语言:javascript
运行
复制
public static void testsForLinkedLists(int potencia,
        int repeticoesteste, int somarAoArray, String ficheiroExcel,
        int validararray, IntToDoubleFunction pushMethod)

你可以这样调用它:

代码语言:javascript
运行
复制
testsForLinkedLists(...., measuring_tests::timeToPushLinkedStack);
票数 0
EN

Stack Overflow用户

发布于 2017-04-12 23:14:09

好的。我明白了:)试着看一下本教程:https://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html也可以通过以下方式获取方法: fooMethod = MyObject.class.getMethod("foo")

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43372745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档