【问题标题】:Dynamic object creation with arguments使用参数创建动态对象
【发布时间】:2020-11-11 23:16:39
【问题描述】:

场景: 这是以下博客中提到的要求的修改版本。

How to create map[String,Class] and create its object dynamically in scala

我有一个场景,我需要一个一个地调用类,它根据用户的输入提供者实现特征,如果没有提供,它应该调用其中的所有处理器类和 process() 方法。

trait Processor {
  def process(str:String)=println("default process")
}
case class ProcessorOne() extends Processor
case class ProcessorTwo() extends Processor {
  override def process(str:String)=println("process:"+str)
}
case class ProcessorThree() extends Processor {
  override def process(str:String)=println("process:"+str)
}

现在我的问题是如何创建一个 Map[String,Class] 以根据用户输入键动态选择特定类并传递用户传递的特定参数。

val myFuncs =
  Map("string1" -> (() => ProcessorOne().process),
    "string2" -> (() => ProcessorTwo().process),
  "string3" -> (() => ProcessorThree().process))

如果用户说 string2 作为键,其对应的类参数是 15。 我应该将输出作为 process:15。

如果用户将 string3 作为键和类参数作为 20 传递。那么应该调用处理器 3 的相应对象并输出 process:20。应该打印出来。

我是 scala 的新手。请给我建议。欢迎使用任何其他使用用户提供的参数动态选择 scala 类的方法。

【问题讨论】:

  • 我不明白,问题是什么?如何使用地图?如何神奇地创建地图?

标签: scala scala-collections


【解决方案1】:

您实际上不需要“动态选择”类。 您想获得一个函数,该函数会创建所选类的新对象。 你的变种

val myFuncs =
  Map("string1" -> (() => ProcessorOne().process),
      "string2" -> (() => ProcessorTwo().process),
      "string3" -> (() => ProcessorThree().process))

相当不错。

假设我们将用户输入作为函数的参数

object SomeServiceThatProcessUserInput {
  private val implementationCreators: Map[String, () => Processor] = 
    Map(
      "string1" -> () => ProcessorOne(),
      "string2" -> () => ProcessorTwo(),
      "string3" -> () => ProcessorThree()
    )

  def processUserInput(implementationChooseString: String, anotherInput: String) = {
    val implementationCreator: () => Processor = implementationCreators .get(implementationChooseString).getOrElse(throw new Exceprtion())
    val implementation: Processor = implementationCreator()
    implementation.process(anotherInput)
  }
}

你根本不需要处理Class。

如果您想使用带有额外.process 的地图:

object SomeServiceThatProcessUserInput {
  private val implementationFunctionCreators: Map[String, () => String => Unit] = 
    Map(
      "string1" -> () => ProcessorOne().process,
      "string2" -> () => ProcessorTwo().process,
      "string3" -> () => ProcessorThree().process
    )
  def processUserInput(implementationChooseString: String, anotherInput: String) = {
    val implementationFunctionCreator: () => String => Unit = implementationFunctionCreators.get(implementationChooseString).getOrElse(throw new Exceprtion())
    val implementationFunction: String => Unit= implementationFunctionCreator()
    implementationFunction(anotherInput)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 2011-04-23
    • 2023-03-29
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多