【问题标题】:Scala - Create a new Class on runtime based on dynamic dataScala - 基于动态数据在运行时创建一个新类
【发布时间】:2015-10-30 15:23:19
【问题描述】:

我有一个字符串数组,我将从任意函数接收。我想使用数组的元素在运行时创建一个新类(不是现有类的新对象)。举个例子吧

val keyCounts = Array[String]

def newDomainPartioner(keyCounts : Array[Strings]) : DomainPartitioner{
    return class DomainPartitioner with Serializable {
        def getPartition(key: Any): Int = key match {

          case <first element of keyCount> => 
            1
          case <second element of keyCount> =>
            1
          case <third element of keyCount> =>  
            1
          case <forth element of keyCount> => 
            1
          case _ => 0
        }

      }
}

有没有办法实现预期的功能?

【问题讨论】:

  • 您确定需要这样做吗?

标签: scala


【解决方案1】:

您可以在运行时使用反射生成一个新类,详情请参阅此问题:

Generating a class from string and instantiating it in Scala 2.10

但是,听起来您最好拥有一个包含您想要的行为的类,并返回该类的实例,例如:

class DomainPartitioner(keyCounts: Array[String]) with Serializable {
    def getPartition(key: Any): Int = keyCounts indexOf key match {
      case 1 => 
        1
      case 2 =>
        1
      case 3 =>  
        1
      case x if myConditionIsTrue(x) => 
        1
      case _ => 0
    }

  }

def newDomainPartioner(keyCounts : Array[Strings]) =
    new DomainPartitioner(keyCounts)

【讨论】:

  • 你的方法似乎是一个很好的方法,但它可以推广到 keyCounts arr 的任意数量的元素。我刚刚提到了前四个作为示例,但我需要一个解决 keyCounts arr 任意数量元素的解决方案
  • 你使用数组索引作为case变量,我希望能够使用实际的数组元素。
  • 我在 case 语句中添加了另一行来展示如何推广到任何条件。这能解决你的问题吗?
【解决方案2】:
val arrayStrings: Array[String] = Array("we","are","great")

def arrayCaseClass(schema:Array[String], className:String)
:String = {
  def arrayElements(element:String):String = {
    val types = element
    element match {
      case x if !x.isEmpty => s"  $element:String"
      case _ => s"  $element:$types"
    }
  }

  val fieldsName = schema.map(arrayElements).mkString(",\n  ")
  s"""
     |case class $className (
     |  $fieldsName
     |)
""".stripMargin
}


println(arrayCaseClass(arrayStrings, "ArrayCaseClass"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2011-02-01
    相关资源
    最近更新 更多