vendredi 17 novembre 2017

Converting Map[String, Object] to case class with casting values using scala reflect

I have some case class

MyCaseClass(a:Option[Int], b:Option[Int])

and i want map Map[String, Object] to my case class with casting Object(almost always String) to the right type. For this i am using next function:

def createCaseClass2[T](vals : MutableMap[String, Object])(implicit cmf : ClassTag[T]) = {
  val ctor = cmf.runtimeClass.getConstructors().head
  var types:Map[String,String] = Map()
  typeOf[MyCaseClass].members.filter(!_.isMethod).map(row=> types += (row.name.toString.trim-> row.typeSignature.toString))
  val args = cmf.runtimeClass.getDeclaredFields().map( f =>try{
    types(f.getName).toString match{
      case "scala.Option[scala.Int]"=>  try{
        Some(vals(f.getName).asInstanceOf[Option[String]].get.toInt)
      } catch {case e: Exception=>  None}
      case "scala.Option[scala.Double]" =>  try{
        println(vals(f.getName))
        Some(vals(f.getName).asInstanceOf[Option[String]].get.toDouble)
      } catch {case e: Exception =>  None}
      case _ =>   vals(f.getName)
    }
  } catch{case e:Exception=>
          println(e.getMessage)
    None})

  ctor.newInstance(args : _*).asInstanceOf[T]
}

i don't want pass MyCaseClass and i want replace code typeOf[MyCaseClass]. How i can realize it ?





Aucun commentaire:

Enregistrer un commentaire