vendredi 18 septembre 2015

Scala reflection - Java enum generic object

I am using Scala 2.10 and I am struggling with following generic method for deserialization of java enums.

class FromEnumFormat[T<: Enum[T]] extends JsonFormat[T] {

  import scala.reflect._
  implicit val m = classTag[T]

  override def read(json: JsValue): T = {

    val EnumerationClass  = m.runtimeClass.asInstanceOf[Class[T]]

    json match {
      case s :JsString if EnumerationClass.getEnumConstants.map(_.toString.toLowerCase).contains(s) => Enum.valueOf(EnumerationClass ,s.value.toUpperCase()).asInstanceOf[T]
      case unknown => deserializationError(s"unknown Status: ${unknown}")
    }
  }

  override def write(obj: T): JsValue = {JsString(obj.name().toLowerCase)}
}

The errror message I am getting is :

 No ClassTag available for T

which is kind of obvious but I don't know how to solve it correctly. Could someone give me a hint?





Aucun commentaire:

Enregistrer un commentaire