2017-08-29 149 views
1

字符串數組我有一個案例類,如下所示:
case class MHealthUser(acc_Chest_X: Double, acc_Chest_Y: Double, acc_Chest_Z: Double, activityLabel: Int)轉換案例類構造函數的參數在斯卡拉

這些形成斯巴克據幀,這就是爲什麼我使用的情況下,類的模式。我只是想將它們映射到Array[String],所以我可以在Spark中使用ParamValidators.inArray(attributes)方法。我用下面的代碼使用反射來構造參數到陣列映射:

val attributes: Array[String] = MHealthUser.getClass.getConstructors.map(a => a.toString) 

但這僅僅給我長度1的陣列,而我想長度爲4的陣列,其中所述陣列是所述的內容我定義的數據集模式,作爲一個字符串。否則,我使用數據集模式的硬編碼值,這顯然不雅觀。 換句話說,我希望輸出:

val attributes: Array[String] = Array("acc_Chest_X", "acc_Chest_Y", "acc_Chest_Z", "activityLabel") 

我一直在玩了一會兒,並不能得到它的工作。任何想法讚賞。謝謝!

回答

0

我會使用ScalaReflection

import org.apache.spark.sql.catalyst.ScalaReflection 
import org.apache.spark.sql.types.StructType 

ScalaReflection.schemaFor[MHealthUser].dataType match { 
    case s: StructType => s.fieldNames 
    case _ => Array[String]() 
} 

外觸發看到Scala. Get field names list from case class