猿问

如何从Java中的参数调用不同的方法?

假设我有一个类中的方法 A 和 B:


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

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

现在,我有另一个可能使用 A 或 B 的函数。但在调用它们之前,我会先做一些逻辑:


void C() {

 // lots of logic here

 invoke A or B

 // lots of logic here 

}

我想将方法 A 或 B 作为 C 的参数传递,例如:


void C(Function<> function) {

 // lots of logic here

 invoke function (A or B)

 // lots of logic here 

}

但是,我注意到Java中的Function类只能接受一个参数(方法A或B都有两个参数)。有解决方法吗?(我不想更改方法 A 或 B 签名)。


慕神8447489
浏览 348回答 2
2回答

慕婉清6462132

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

倚天杖

您可以通过 lambda 表达式使用和编写自己的函数式接口。我在这里说明,interface MyInterface<T> {&nbsp; &nbsp; List<T> f(int start, int size);}class Example {&nbsp; &nbsp; List<String> A(int start, int size) {&nbsp; &nbsp; &nbsp; &nbsp; return new ArrayList<String>();&nbsp; &nbsp; }&nbsp; &nbsp; List<Integer> B(int start, int size) {&nbsp; &nbsp; &nbsp; &nbsp; return new ArrayList<Integer>();&nbsp; &nbsp; }&nbsp; &nbsp; void C(MyInterface function) {&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Example e = new Example();&nbsp; &nbsp; &nbsp; &nbsp; MyInterface<String> methodForA = (x,y) -> e.A(1,2);&nbsp; &nbsp; &nbsp; &nbsp; MyInterface<Integer> methodForB = (x,y) -> e.B(1,2);&nbsp; &nbsp; &nbsp; &nbsp; e.C(methodForA);&nbsp; &nbsp; &nbsp; &nbsp; e.C(methodForB);&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答