[英]Scala classOf for type parameter, revisited
Following on from: 继续之后:
Scala classOf for type parameter Scala classOf用于类型参数
I've tried implementing it but seem to get some weird generics problem, actually I've muddled my way through a couple of them now, but this is as close to correct I can get it... 我已经尝试过实现它,但似乎得到了一些奇怪的泛型问题,实际上我现在已经混淆了他们的几个,但这是接近正确我可以得到它...
I'm using the Scala - Jackson JSON bindings (excellent lib by the way, much easier than SJson) 我正在使用Scala - Jackson JSON绑定(顺便说一句优秀的lib,比SJson容易得多)
def genparseResult[T: ClassManifest](t: T,s:String):Either[Tuple2[JsonParseException,String],T] = {
try{
val res = jsonSerializer.readValue(s, classManifest[T].erasure)
Right(res)
}
catch{
case jpe:JsonParseException => Left((jpe,s))
}
}
Anyhow, the code above is generating the following compile error: 无论如何,上面的代码生成以下编译错误:
type mismatch; 类型不匹配; found : res.type (with underlying type Any) required: T 发现:res.type(底层类型为Any)必需:T
I'm confused as hell. 我很困惑。 Should the code above be able to work? 上面的代码应该可以工作吗?
Update following input from tenshi, I post the completed class 更新 以下来自tenshi的输入,我发布完成的课程
import com.fasterxml.jackson.core.JsonParseException
object DatasiftJsonMapper {
import java.util.Date
import com.fasterxml.jackson.databind.{ Module, ObjectMapper }
import com.fasterxml.jackson.module.scala.DefaultScalaModule
val jsonSerializer = {
val m = new ObjectMapper()
m.registerModule(DefaultScalaModule)
m
}
def parseDSResult(s: String): Either[Tuple2[JsonParseException, String], DatasiftResult] = {
genparseResult(classOf[DatasiftResult], s)
}
def parseQRegRequest(s: String): Either[Tuple2[JsonParseException, String], QRegRequest] = {
genparseResult(classOf[QRegRequest], s)
}
def genparseResult[T: ClassManifest](t: Class[T], s: String): Either[Tuple2[JsonParseException, String], T] = {
try {
val res = jsonSerializer.readValue(s, classManifest[T].erasure).asInstanceOf[T]
Right(res)
} catch {
case jpe: JsonParseException => Left((jpe, s))
}
}
}
As far as I remember, classManifest[T].erasure
returns Class[_]
instead of Class[T]
, so the result of jsonSerializer.readValue(...)
would be or type Any
. 据我classManifest[T].erasure
返回Class[_]
而不是Class[T]
,因此jsonSerializer.readValue(...)
的结果将是或者类型为Any
。 You can try to cast parsing result: 您可以尝试转换解析结果:
val res = jsonSerializer.readValue(s, classManifest[T].erasure).asInstanceOf[T]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.