gpt4 book ai didi

使用 lambdas/方法引用的 java 8 事件监听器/调度程序 - 如何实现某些事情?

转载 作者:行者123 更新时间:2023-11-30 08:22:32 28 4
gpt4 key购买 nike

我正在尝试使用新添加的 lambda 在 Java 中编写事件引擎。如果以下代码可以工作,我将非常高兴:

public class Test
{
public Test()
{
EventEngine.listen(EventType.THIS, self::thisEventCallback);
EventEngine.listen(EventType.THAT, self::thatEventCallback);
EventEngine.listen(EventType.OTHER, (other) -> other.doX());
}

private void thisEventCallback()
{
// do whatever here
}

private boolean thatEventCallback(SomeObject parameter)
{
return parameter.someCheckOrWhatever();
}
}

据我所知,我必须定义一个通用的空接口(interface),例如,public interface Listener {//nothing here},并通过各种其他接口(interface)为每种事件类型扩展它所以我可以在必要时指定不同的参数和返回类型。显然,这需要将回调强制转换为 EventEngine 的触发方法内的特定接口(interface),但我对此没有问题。

但是,在此之前,我需要了解如何将我定义的这些私有(private)方法引用到 EventDispatcher.listen 方法中。 self::thisEventCallback 不起作用。有没有办法在 Java 8 中做到这一点,还是只能在 Scala 中实现?

如果不是,那么您建议使用什么替代方法而不涉及为每个监听器/回调创建新对象?

最佳答案

    EventEngine.listen(EventType.THIS, this::thisEventCallback);
EventEngine.listen(EventType.THAT, this::thatEventCallback);
EventEngine.listen(EventType.OTHER, (other) -> other.doX());

所以 this 而不是 self

并且您需要具有与回调具有相同签名的一个抽象方法的功能接口(interface)。

public interface THISInterface {
public void thisEventCallback();
}

public interface THATInterface {
public boolean thatEventCallback(SomeObject parameter)
}

class EventEngine {
public void listen(Type t, THISInterfcace thisCallback) {
thisCallback.thisEventCallback();
}
public void listen(Type t, THATInterfcace thatCallback) {
boolean ok = thatCallback.thatEventCallback();
}
...
}

但是已经有很多functional interfaces预定义的,你应该需要学习。例如,在这里,不需要自己的接口(interface)。

class EventEngine {
public void listen(Type t, Consumer<Void> thisCallback) {
thisCallback.accept();
}
public void listen(Type t, Predicate<Void> thatCallback) {
boolean ok = thatCallback.test();
}

以上是否正确,我不确定(目前深入 java 6 - 叹气)。

关于使用 lambdas/方法引用的 java 8 事件监听器/调度程序 - 如何实现某些事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24285861/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com