我正在尝试将 Scala 中以字符串形式保存在数据库中的表达式转换回工作代码。
我尝试过Reflect Toolbox、Groovy等,但似乎无法达到我的要求。
这是我尝试过的:
import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
val toolbox = currentMirror.mkToolBox()
val code1 = q"""StructType(StructField(id,IntegerType,true), StructField(name,StringType,true), StructField(tstamp,TimestampType,true), StructField(date,DateType,true))"""
val sType = toolbox.compile(code1)().asInstanceOf[StructType]
我需要使用sType实例将customSchema传递到csv文件以创建数据帧,但它似乎失败了。
有什么方法可以将 StructType 的字符串表达式转换为实际的 StructType 实例吗?任何帮助将不胜感激。
最佳答案
如果 StructType 来自 Spark 并且您只想将 String 转换为 StructType,则不需要反射。你可以试试这个:
import org.apache.spark.sql.catalyst.parser.LegacyTypeStringParser
import org.apache.spark.sql.types.{DataType, StructType}
import scala.util.Try
def fromString(raw: String): StructType =
Try(DataType.fromJson(raw)).getOrElse(LegacyTypeStringParser.parse(raw)) match {
case t: StructType => t
case _ => throw new RuntimeException(s"Failed parsing: $raw")
}
val code1 =
"""StructType(Array(StructField(id,IntegerType,true), StructField(name,StringType,true), StructField(tstamp,TimestampType,true), StructField(date,DateType,true)))"""
fromString(code1) // res0: org.apache.spark.sql.types.StructType
代码取自 Spark 的 org.apache.spark.sql.types.StructType
伴随对象。您不能直接使用它,因为它位于私有(private)包中。此外,它使用 LegacyTypeStringParser
因此我不确定这对于生产代码是否足够好。
关于string - 将字符串表达式转换为实际工作实例表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56618536/