gpt4 book ai didi

scala - 如何根据类名创建 Akka Actor

转载 作者:行者123 更新时间:2023-12-03 18:19:49 25 4
gpt4 key购买 nike

我想使用类名创建一个 Akka Actor ,如图所示。
我已经尝试了 system.actorOf(new Props(theProcessor.getClass), name = "Test") 的许多变体,
但我就是无法让它发挥作用。从类加载器创建 Actor 的任何想法

package com.test

import akka.actor.{Props, Actor, ActorRef, ActorSystem}

object Main {
def main(args: Array[String]) {
ActorFromString("Test")
}
}

object ActorFromString {
implicit val system = ActorSystem("Test")
def apply(name: String): ActorRef = {
val className = "com.test." + name + "Processor"
val theProcessor: Actor = Class.forName(className).newInstance().asInstanceOf[Actor]
system.actorOf(new Props(theProcessor.getClass), name = "Test")
}
}

class TestProcessor extends Actor {
def receive = {
case data => println("processing data")
}
}

Exception in thread "main" akka.actor.ActorInitializationException:
You cannot create an instance of [com.test.TestProcessor] explicitly using the constructor (new).
You have to use one of the factory methods to create a new actor. Either use:
'val actor = context.actorOf(Props[MyActor])' (to create a supervised child actor from within an actor), or
'val actor = system.actorOf(Props(new MyActor(..)))' (to create a top level actor from the ActorSystem)
at akka.actor.ActorInitializationException$.apply(Actor.scala:166)
at akka.actor.Actor$class.$init$(Actor.scala:377)
at com.test.TestProcessor.<init>(ActorFromString.scala:20)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:374)
at java.lang.Class.newInstance(Class.java:327)
at com.test.ActorFromString$.apply(ActorFromString.scala:15)
at com.test.Main$.main(ActorFromString.scala:7)
at com.test.Main.main(ActorFromString.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Process finished with exit code 143

最佳答案

您可以使用 Java API(仅用于 Props 实例化):

val myActor = system.actorOf( 
new Props( Class.forName( "myActorClassName" ).asInstanceOf[Class[Actor]] )
)

重要的部分是 new关键词。如果省略它,您将改用 Scala API,它不允许按类进行实例化。

关于scala - 如何根据类名创建 Akka Actor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15675227/

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