如何将参数传递给可运行方法

问题描述 投票:0回答:2

我有一个函数functionAcceptsMethod,它接受可运行方法作为参数,我想通过传递带有参数的方法来调用functionAcceptsMethod

当我通过不带参数传递来调用functionAcceptsMethod时很好,但是如何传递带参数的函数。

这里是一个例子

 private void testFun() {
        functionAcceptsMethod(this::funWithoutParams);
        functionAcceptsMethod(this::funWithParams); // this where I need to pass params
        //functionAcceptsMethod(() -> funWithParams("abcd")); // I tried this, is this the right 
         //way?
    }

private void funWithoutParams() {
    //do something
}

private void funWithParams(String testString) {
    //do something
}

private  void functionAcceptsMethod(Runnable method) {
    method.run();
}
java android runnable
2个回答
0
投票
java.util.function

可以,如果您的目的只是传递方法引用并在java.util.function方法的参数中获取args,然后将functionAcceptsMethod(() -> funWithParams("abcd"));用作函数接收器参数

© www.soinside.com 2019 - 2024. All rights reserved.