Akka - 使用反射创建演员

发布于 2024-12-12 19:33:19 字数 456 浏览 3 评论 0原文

我需要创建一个演员,其确切类型只能在运行时从配置文件中读取。该参与者的构造函数并不简单,即它需要一些在配置文件中定义的参数。

到目前为止,我尝试使用反射来执行此操作,如下所示:

val actor = actorOf(constructor.newInstance(parameters: _*).asInstanceOf[T]).start

不幸的是,这会导致“akka.actor.ActorInitializationException:ActorRef for example of actor [...] is not inscope. You can not create an instance of演员明确使用“new MyActor”[...]”!

现在,我知道这可以保护框架免于泄漏对内部对象的引用,但我怎样才能解决这个问题呢?或者,我还能怎样以一种可行的方式做我想做的事情呢?

I need to create an actor whose exact type is only read at runtime from a configuration file. The constructor for that actor is non trivial, i.e. it requires some parameters which are defined in the configuration file.

Until now, I've tried to do this using reflection as follows:

val actor = actorOf(constructor.newInstance(parameters: _*).asInstanceOf[T]).start

Unfortunately, this results in an "akka.actor.ActorInitializationException: ActorRef for instance of actor [...] is not in scope. You can not create an instance of an actor explicitly using 'new MyActor'. [...]"!

Now, I understand this protects the framework from leaking a reference to the inner object, but how can I get past this problem? Alternatively, how else could I do what I'm trying to do in a way that will work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情仇皆在手 2024-12-19 19:33:19

也许可以使用 Java 接口来创建带有参数的 actor。用于创建的(Java)代码如下所示:

ActorRef actor = actorOf(new UntypedActorFactory() {
  public UntypedActor create() {
    return new MyUntypedActor("service:name", 5);
   }
});

因此您传递一个工厂而不是一个函数。这可能效果更好...

Maybe use the Java interface for creating actors with parameters. The (Java) code for creation looks like this:

ActorRef actor = actorOf(new UntypedActorFactory() {
  public UntypedActor create() {
    return new MyUntypedActor("service:name", 5);
   }
});

So you pass a factory instead of a function. This might work better...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文