无法捕获scala中的ClassCastException

无法捕获scala中的ClassCastException,scala,exception-handling,pattern-matching,Scala,Exception Handling,Pattern Matching,我在捕获ClassCastException时遇到一些问题。 它发生在检索函数的模式匹配的最后一种情况中,异常不是cougt 我怎样才能解决这个问题 abstract class Property object EmptyProperty extends Property class PropertyCompanion[T] object Type extends PropertyCompanion[Type] case class Type extends Prope

我在捕获ClassCastException时遇到一些问题。 它发生在检索函数的模式匹配的最后一种情况中,异常不是cougt

我怎样才能解决这个问题

  abstract class Property

  object EmptyProperty extends Property

  class PropertyCompanion[T]

  object Type extends PropertyCompanion[Type]
  case class Type extends Property

  object Name extends PropertyCompanion[Name]
  case class Name extends Property

  abstract class Entity {
    protected val properties: Map[PropertyCompanion[_], Property]
    def retrieve[T](key: PropertyCompanion[T]) =
      properties.get(key) match {
        case Some(x) => x match {
          case EmptyProperty => throw new Exception("empty property")
          case _ => {
            try {
              x.asInstanceOf[T]
            } catch {
              case e => throw new Exception("fubar")
            }
          }
        }
        case None => throw new Exception("not found")
      }
  }

  case class Book(protected val properties: Map[PropertyCompanion[_], Property]) extends Entity {
    def getType = retrieve(Type)
    def getName = retrieve(Name)
  }

  object Test extends App {

    val book = Book(Map(Type -> Type(), Name -> Type()))
    val name = book.getName
  }

您无法捕获异常,因为您无法强制转换到t。JVM在运行时不知道t,因此您必须对它进行一些欺骗;-)。将
隐式m:CLassManifest[T]
传递给您的方法,并使用
m.erasure.cast(x)
。您的应用程序可能如下所示:

abstract class Property

object EmptyProperty extends Property

class PropertyCompanion[T]

object Type extends PropertyCompanion[Type]
case class Type extends Property

object Name extends PropertyCompanion[Name]
case class Name extends Property

abstract class Entity {
  protected val properties: Map[PropertyCompanion[_], Property]
  def retrieve[T](key: PropertyCompanion[T])(implicit m: ClassManifest[T]) =
    properties.get(key) match {
      case Some(x) => x match {
        case EmptyProperty => throw new Exception("empty property")
        case _ => {
          try {
            m.erasure.cast(x).asInstanceOf[T]
          } catch {
            case e => throw new Exception("fubar")
          }
        }
      }
      case None => throw new Exception("not found")
    }
}

case class Book(protected val properties: Map[PropertyCompanion[_], Property]) extends Entity {
  def getType = retrieve(Type)
  def getName = retrieve(Name)
}

object Test extends App {

  val book = Book(Map(Type -> Type(), Name -> Type()))
  val name = book.getName
}

编辑:为T添加了一个cast以获得正确的返回类型

非常感谢。因此,如果不使用清单,就无法实现这一点?它会带来性能成本吗?我还必须返回
结果。作为[T]
的实例,因为它会返回
Any
类型。你是对的,我看到了同样的行为,这很奇怪,因为
Class[T]
的javadoc显示了这个符号:
T cast(Object obj)
。我不认为还有其他方法,因为scala就是通过这种方法来实现类型擦除的。除了额外的对象分配之外,性能成本应该不会更多。@drexin可能是这样,但是
m.erasure
不会返回
Class[T]