gpt4 book ai didi

java Akka 。如何将参与者的行为与许多泛型相匹配

转载 作者:行者123 更新时间:2023-11-30 06:38:24 25 4
gpt4 key购买 nike

我是 akka 的初学者,在我的学习过程中我有下一个问题:

例如,我有一个主要 Actor ,它向其他两个 child Actor 发送消息。他们都会返回不同的列表。

    ChildActorA return Optional<List<Entity1>>
ChildActorB return Optional<List<Entity2>>

我如何匹配主角来处理这些回复?

一些演示代码:

    public class MainActor extends AbstractLoggingActor {

@Override
public Receive createReceive() {
return receiveBuilder()
.match(Entity1.class, this::onEntity1)
.match(Entity2.class, this::onEntity2)
//How match to the list of these entities?
.match(Optional<List<Entity1>>, this::onList1)
.match(Optional<List<Entity2>>, this::onList2)
.build();
}
}


private void onEntity1(Entity1 entity1) {
final ActorRef entity1ChildActor = getContext().actorOf(Entity1ChildActor.props());

entity1ChildActor.tell("printIt", getSelf());
}

private void onEntity2(Entity2 entity2) {
final ActorRef entity21ChildActor = getContext().actorOf(Entity2ChildActor.props());

entity2ChildActor.tell("printIt", getSelf());
}

child Actor 之一:

public class Entity1ChildActor extends AbstractLoggingActor {

@Override
public Receive createReceive() {
return receiveBuilder()
.match(String.class, this::onPrint)
.build();
}

private void onPrint(Entity1 entity1) {
System.out.println(entity1);

//Here I want to tell to parent List of something
//namely Optional<List<Entity1>>
//How can I match parent behavior?

getSender().tell(someOptionalList, getSelf());
}

public static Props props(){
return Props.create(Entity1ChildActor.class);
}
}

最佳答案

泛型类型参数是编译时需要考虑的问题。它们在运行时丢失。它的名字叫type erasure 。所以在运行时 Optional<List<Entity1>>Optional<List<Entity2>>变得简单Optional并且按类型无法区分。

但是,您可以创建 2 个具体类用作消息并封装可选列表并与这些列表进行匹配。或者,您可以创建 1 个具体类,让它在字段中保存实体的类型并公开它,以便您可以在 match 方法的谓词中使用它。

关于 java Akka 。如何将参与者的行为与许多泛型相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44844213/

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