【问题标题】:Get class from Object in the run time in scala在scala的运行时从Object获取类
【发布时间】:2016-10-30 16:39:43
【问题描述】:
import org.apache.spark.sql.types.StructField
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.types.StringType
import org.apache.spark.sql.type.NumericType
import org.apache.spark.sql.type.BooleanType
   ....
   ....
val TableSchema = Array(
      ("ID", IntegerType),
      ("Name", StringType),
      ("TNum", integerType),
      ("Handled", BooleanType),
      ("Value", StringType)
      )

我有一个表的架构信息数组,我正在尝试将其映射到可用于创建 spark 数据框的结构。转换后的数组应该如下:

val struct = Array(
 StructField("ID", NumericType),
 StructField("Name", BooleanType),
 StructField("TNum", NumericType),
 StructField("Handled", BooleanType),
 StructField("Value", StringType))

所以我正在尝试编写一个将每个元素转换为 StructField 的方法。这是我的尝试:

    def mapToStruct(arr:Array[(String, String, Object)])={
     val newArr = arr.map(ele => StructField(ele._1, ele._2))
     newArr
   }

在这种情况下,我无法从方法 mapToStruct 的第三个参数中获取 StringTypeBooleanTypeIntegerType 的类。我得到的例外是type mismatch; found : Object required: org.apache.spark.sql.types.DataType。但是如果我把参数类型改成Array[(String, String, DataType)],就和变量类型不匹配了。

我的问题是我应该为方法 mapToStruct 的第三个参数选择什么数据类型,然后我可以在运行时获取该对象的类。
提前致谢。

【问题讨论】:

  • “它与变量类型不匹配”是什么意思。 ?
  • @parmu type mismatch; found : Array[(String, String, org.apache.spark.sql.types.AtomicType with Product with Serializable)] required: Array[(String, String, org.apache.spark.sql.types.DataType)] Note: (String, String, org.apache.spark.sql.types.AtomicType with Product with Serializable) <: string org.apache.spark.sql .types.datatype array t _ org.apache.spark.sql.types.datatype>

标签: scala apache-spark reflection dataframe


【解决方案1】:

这应该可行:

import org.apache.spark.sql.types.

val tableSchema: Array[(String, DataType)] = Array(
  ("ID", IntegerType),
  ("Name", StringType),
  ("Handled", BooleanType),
  ("Value", StringType)
  )

def mapToStruct(arr: Array[(String, DataType)]): Array[StructField] = arr.map(e => StructField(e._1, e._2))

【讨论】:

  • 谢谢,它有效。你能解释一下为什么类型推断不能为 tableSchema 设置正确的数据类型吗?
猜你喜欢
  • 2021-02-04
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 2018-04-21
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多