作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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/
我是一名优秀的程序员,十分优秀!