【发布时间】:2017-08-16 21:08:19
【问题描述】:
在 Java 和 Scala 中,我将如何执行以下操作:
我希望能够将函数作为参数传递给函数,其中函数参数有所不同。例如,这就是我现在在 Java 中被锁定的内容:
public void doSomething(Object object, Action1<Object> function) {
function.call(object);
}
public void doOtherThing(Object obj) {
System.out.println(obj);
}
doSomething("hello", this::doOtherThing);
这就是我想要做的:
public void doSomethingFancy(Object object, <Some Function Type Here> function) {
function.call(object);
}
public void doFancyThing(Object obj1, String str1, List list1) {
// do stuff
}
public void doFancyThing2(Object obj1, RandomObj rObj, Integer int1) {
// do stuff
}
...
doSomething("hello", this::doFancyThing);
doSomething("hello", this::doFancyThing2);
基本上我希望输入函数具有可变类型的输入参数。 ActionN 不起作用,因为这会将对象数组传递给我的 doFancyThing 方法,并且显然无法编译。
【问题讨论】:
-
制作自定义界面。
-
方法签名过载?你有一组特定的输入参数吗?
-
更新问题
标签: java scala java-8 metaprogramming covariance