scala - 如何从有界泛型类型中获取类

标签 scala generics enums

我正在尝试为 Json4s 编写一个通用的自定义序列化程序,它可以处理类型为 T <: Enum[T] 的 Java 枚举。为此,我想使用 Enum.valueOf 方法,该方法采用类型也为 T <: Enum[T] 的类标记。这是我到目前为止所拥有的:

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())
  }
}

但我得到以下编译错误:

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]

我不知道如何让 enumerationClass 具有正确的类型。

最佳答案

enumerationClass 在您的 deserialize 方法中 shadows 在其外部定义的 val enumerationClass。您的代码相当于:

case (t @ TypeInfo(a, _), json) => {
  json match {
    case JString(value) => Enum.valueOf(a, value.toUpperCase()).asInstanceOf[T]
    case value => throw new MappingException(s"Can't convert $value to $enumerationClass")
  }
}

这不是您想要的:这将始终匹配,因为您不限制类。您需要使 enumerationClass 成为稳定的标识符,即在这里将其设为大写。参见 this questionanswer阅读更多相关内容。

class EnumSerializer[T <: Enum[T]](implicit m: Manifest[T]) extends Serializer[T] {

  val EnumerationClass = 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")
      }
    }
  }

  ...
}

关于scala - 如何从有界泛型类型中获取类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17268633/

相关文章:

Scala 宏注解不会扩展(宏天堂)

c# - 将 PropertyInfo 转换为通用类型

c# - 请帮助我理解在 C# 中使用泛型时的多态性

java - 作为返回类型的一部分,尖括号是什么意思? <T> T

c++ - 是否有建议让 c++ 使用短枚举值的上下文?

java - 枚举中的静态 final方法

scala - 如何用 csv 数据解析一个巨大的文件并在普通 Scala 中计算其一列的平均值?

scala - 在 Scala 中绑定(bind)类型之后的另一个子类型

Scala:为什么 Float.floatToIntBits(2f) 失败?

c# - 为什么在调试时而不是在运行时检查时会出现异常/从数据库映射枚举的最佳实践是什么