gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:07:51 25 4
gpt4 key购买 nike

我正在尝试为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com