I'm trying to write a generic custom serializer for Json4s that can handle Java enums, which have type T <: Enum[T]. To do this I want to use the Enum.valueOf method, which takes a class token also of type T <: Enum[T]. This is what I have so far:
class EnumSerializer[T <: Enum[T]](implicit m: Manifest[T]) extends Serializer[T] {
val enumerationClass: Class[_ <: Enum[T]] = m.runtimeClass.asInstanceOf[Class[T]]
def deserialize(implicit format: Formats) : PartialFunction[(TypeInfo, JValue), T] = {
case (t @ TypeInfo(enumerationClass, _), json) => {
json match {
case JString(value) => Enum.valueOf(enumerationClass, value.toUpperCase()).asInstanceOf[T]
case value => throw new MappingException(s"Can't convert $value to $enumerationClass")
}
}
}
def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case i : Enum[T] => JString(i.name())
}
}
But I get the following compilation error:
inferred type arguments [_0] do not conform to method valueOf's type parameter bounds [T <: Enum[T]]
case JString(value) => Enum.valueOf(enumerationClass, value.toUpperCase()).asInstanceOf[T]
I can't figure out how to get enumerationClass to have the correct type.