Scala - 基于动态数据在运行时创建新类

时间:2015-10-30 15:23:19

标签: scala

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

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
        }

      }
}

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

2 个答案:

答案 0 :(得分:3)

您可以使用反射在运行时生成新类,有关详细信息,请参阅此问题:

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)

答案 1 :(得分:0)

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"))