如何在Scala中创建map [String,Class]并动态创建其对象 [英] How to create map[String,Class] and create its object dynamically in scala

查看:225
本文介绍了如何在Scala中创建map [String,Class]并动态创建其对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:我有一个问题,我需要一个一个地调用处理器类,这是用户输入提供程序所必需的,如果未提供,则应该调用其中的所有处理器类和process()方法.

Scenario : I have a senario where I need to call Processor class one by one , which are required by the input provider by user , if not provided it should call all Processor class and process() method inside it.

代码:

class OneProcessor{}
class TwoProcessor{}

为此,我正在考虑创建Map [String,instanceOfClass],即:

For this I am thinking of creating a Map[String, instanceOfClass] i.e:

val instanceMap:Map[String,Class] =Map(
    "string1" -> new OneProcessor(),
    "string2" -> new TwoProcessor(),
)

问题:如果用户给定string1,则我需要创建OneProcessor()的实例并执行它的processor()方法.

Question : if given string1 by user I need to create instance of OneProcessor() and execute it processor() method.

如果未向用户提供任何输入,则需要调用Map的所有键,并创建所有类的实例并调用所有类的processor().

If user is not provided any input I need to call all keys of Map , and create instances of all classes and call processor() of all...

如何在 scala 中执行此操作?

推荐答案

这是我的解决方案:

假设所有处理器"都在做类似的事情,我建议从特征中扩展它们,而不是使用通用的类级构造.让我们假设以下结构:

Assuming all "processors" are doing similar things, I suggest extending them all from a trait instead of a using general class level constructs. Let's assume the following structure:

trait Processor {
  def process=println("default process")
}
case class ProcessorOne() extends Processor
case class ProcessorTwo() extends Processor {
  override def process=println("process 2")
}
case class ProcessorThree() extends Processor {
  override def process=println("process 3")
}

我们创建一个地图,并将所有 process 函数放入其中:

We create a map and put all process functions inside it:

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

请注意,这是一个 Map [String,Unit] .由于您的目标是调用函数,因此您实际上不需要在地图中放置实例.

Note that this is a Map[String, Unit]. Since your goal is to invoke functions, you don't really need to put instances in the map.

现在,您可以轻松地调用任何或所有这些功能:

Now you can easily invoke any or all of these functions:

val userInput =""

if(myFuncs isDefinedAt userInput)
  myFuncs(userInput)()
else
  myFuncs.values.foreach(v => v())

上面将输出:

default process
process 2
process 3

因此,如果键不存在于映射中,则将调用所有功能(不按特定顺序),但是,如果键位于映射中,则仅将调用与该键关联的功能.

So if the key is not present in the map, all functions will be invoked (in no particular order), but if the key is in the map, only the function associated with that key will be invoked.

如果还需要功能以特定顺序运行,则可以使用 LinkedHasMap ListMap 创建保留插入顺序的映射.

If you also need the functions to run in a particular order, you can use LinkedHasMap or ListMap to create a map which preserves the insertion order.

这篇关于如何在Scala中创建map [String,Class]并动态创建其对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆