假设我有一个类中的方法 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 签名)。
2 回答
![?](http://img1.sycdn.imooc.com/545868c20001b8c402200220-100-100.jpg)
倚天杖
TA贡献1828条经验 获得超3个赞
您可以通过 lambda 表达式使用和编写自己的函数式接口。我在这里说明,
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);
}
}
添加回答
举报
0/150
提交
取消