简体   繁体   中英

How to invoke different methods from parameters in Java?

Assume that I have a method A and B from a class:

List<String> A(int start, int size);
List<String> B(int start, int size);

Now, I have another function that might use A or B. But before invoking them, I'll do some logic first:

void C() {
 // lots of logic here
 invoke A or B
 // lots of logic here 
}

I want to pass method A or B as parameter of C, something like:

void C(Function<> function) {
 // lots of logic here
 invoke function (A or B)
 // lots of logic here 
}

However, I noticed that the Function class in Java can only accept one parameter (method A or B both have two parameters). Is there a workaround on this? (I don't want to change the method A or B signatures).

BiFunction表示一个接受两个参数并产生结果的函数,因此您可能需要在此处查看

You can use and write your own functional interface by lambda expression. I illustrate here,

interface MyInterface<T> {
    List<T> f(int start, int size);
}

class Example {
    List<String> A(int start, int size) {
        return new ArrayList<String>();
    }

    List<Integer> B(int start, int size) {
        return new ArrayList<Integer>();
    }

    void C(MyInterface function) {

    }

    public static void main(String[] args) {
        Example e = new Example();
        MyInterface<String> methodForA = (x,y) -> e.A(1,2);
        MyInterface<Integer> methodForB = (x,y) -> e.B(1,2);

        e.C(methodForA);
        e.C(methodForB);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM