我正在玩Java 8,以了解如何作为一等公民的功能.我有以下代码段:
package test;
import java.util.*;
import java.util.function.*;
public class Test {
public static void myForEach(List<Integer> list, Function<Integer, Void> myFunction) {
list.forEach(functionToBlock(myFunction));
}
public static void displayInt(Integer i) {
System.out.println(i);
}
public static void main(String[] args) {
List<Integer> theList = new ArrayList<>();
theList.add(1);
theList.add(2);
theList.add(3);
theList.add(4);
theList.add(5);
theList.add(6);
myForEach(theList, Test::displayInt);
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是使用方法引用displayInt将方法传递给方法myForEach.编译器会产生以下错误:
src/test/Test.java:9: error: cannot find symbol
list.forEach(functionToBlock(myFunction));
^
symbol: method functionToBlock(Function<Integer,Void>)
location: class Test
src/test/Test.java:25: error: method myForEach in class Test cannot be applied …Run Code Online (Sandbox Code Playgroud) 这可能听起来像一个奇怪的问题,但有没有办法在Java 8中引用Lambda的标准无操作(即null操作,空模式方法,无操作,无操作方法)方法.
目前,我有一个方法,需要一个,比方说,void foo(Consumer<Object>)我想给它一个无操作,我必须声明:
foo(new Consumer<Object>() {
public void accept(Object o) {
// do nothing
}
}
Run Code Online (Sandbox Code Playgroud)
在哪里我希望能够做到这样的事情:
foo(Object::null)
Run Code Online (Sandbox Code Playgroud)
代替.有类似存在吗?
不确定多参数方法如何工作 - 也许这是Java中lambdas的缺陷.
首先,我不知道如何恰当地表达这个问题,所以这是一个建议。
假设我们有以下重载方法:
void execute(Callable<Void> callable) {
try {
callable.call();
} catch (Exception e) {
e.printStackTrace();
}
}
<T> T execute(Supplier<T> supplier) {
return supplier.get();
}
void execute(Runnable runnable) {
runnable.run();
}
Run Code Online (Sandbox Code Playgroud)
从这张表出发,我从另一个问题中得到了答案
Supplier () -> x
Consumer x -> ()
BiConsumer x, y -> ()
Callable () -> x throws ex
Runnable () -> ()
Function x -> y
BiFunction x,y -> z
Predicate x -> boolean
UnaryOperator x1 -> x2
BinaryOperator x1,x2 -> x3
Run Code Online (Sandbox Code Playgroud)
以下是我在本地得到的结果:
Supplier () -> …Run Code Online (Sandbox Code Playgroud) 什么应该是Java可以用作通用回调机制的首选接口或类似模式?
例如,它可能是类似的东西
public interface GenericCallback
{
public String getID();
public void callback(Object notification);
// or public void callback(String id, Object notification);
}
Run Code Online (Sandbox Code Playgroud)
覆盖hashCode()方法的情况下需要ID,以便被调用者识别调用者.
类似于上述的模式对于需要向条件(例如,处理结束)生成的类报告的对象是有用的.
在这种情况下,"父"类将使用getID()每个GenericCallback对象的方法来跟踪它们,Map<String, GenericCallable>并根据收到的通知添加或删除它们.
此外,如何实际命名这样的接口?
许多人似乎更喜欢Java Observer模式,但是在那里定义的Observable类并不方便,因为它不是绕过单一继承的接口,它承载的功能比上面简单的场景中实际需要的功能要多.