[英]Get class from Object in the run time in scala
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
}
在這種情況下,我不能讓這個類的StringType
, BooleanType
或IntegerType
從方法mapToStruct的第三個參數。 我得到的異常是type mismatch; found : Object required: org.apache.spark.sql.types.DataType
type mismatch; found : Object required: org.apache.spark.sql.types.DataType
。 但是,如果我將參數類型更改為Array [(String,String,DataType)],則它與變量類型不匹配。
我的問題是我應該為方法mapToStruct的第三個參數選擇哪種數據類型,然后可以在運行時獲取此對象的類。
提前致謝。
這應該工作:
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.