动态创建/获取类的类型

时间:2013-12-11 15:36:33

标签: scala

我需要根据命令行参数创建一个actor:

def main(args: Array[String]): Unit = {
  val t = args(0) match {
    // 1
    case 1 => // MyActor1 
    case 2 => // MyActor2
    case 3 => // MyActor3
  }

  // 2
  val app = system actorOf (Props[/* ??? MyActor1(2,3).type? - not working*/], "app")
  app ! "Start"
}

abstract class MyActorBase extends Actor {...}
class MyActor1 extends MyActorBase {...}
class MyActor2 extends MyActorBase {...}
class MyActor3 extends MyActorBase {...}

所以我有两个问题:match应该返回什么以及我应该将哪些内容传递给Props

在C#中我会使用typeof运算符,但是,以下代码在Scala中不起作用MyActor1.type

1 个答案:

答案 0 :(得分:4)

只需要一个合适的关键字(这里我假设您正在使用latest version of Props api):

val actorClass = args(0) match {
   case 1 => classOf[MyActor1]
   case 2 => classOf[MyActor2]
}
val app = system actorOf (Props(actorClass), "app")