简体   繁体   English

在不使用asInstanceOf的情况下在Scala中反序列化XStream中的XML?

[英]Deserializing XML from XStream in Scala without using asInstanceOf?

I'm using XStream in my Scala app with the following thin wrapper: 我在我的Scala应用程序中使用XStream ,使用以下瘦包装器:

import com.thoughtworks.xstream._

object SXStream {
  private val xstream = new XStream

  def fromXML[T](xml: String): T = {
    xstream.fromXML(xml).asInstanceOf[T]
  } 

  def toXML[T](obj: T): String = {
    xstream.toXML(obj)
  } 
}   

Is this the best I'm going to get, or is there a way around that asInstanceOf ? 这是我能得到的最好的,还是有办法解决这个asInstanceOf It looks like casting is the recommended usage in Java; 看起来像是Java中的推荐用法; I'm wondering if Scala provides me some cleaner option. 我想知道Scala是否为我提供了一些更清洁的选择。

You can avoid the asInstanceOf , but the advantages are limited -- the code becomes more idiomatic and you can make the ClassCastException more specific: 您可以避免使用asInstanceOf ,但优点是有限的 - 代码变得更加惯用,您可以使ClassCastException更具体:

def any(xml: String): Any = xml
def fromXML[T: ClassTag](xml: String): T = any(xml) match {
  case a: T => a
  case other => throw new RuntimeException("Invalid type " + other.getClass + " found during marshalling of xml " + xml)
}

On the other hand, this is more verbose and probably less efficient than the asInstanceOf call. 另一方面,这比asInstanceOf调用更冗长,效率可能更低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM