无法在scala中捕获ClassCastException
发布时间:2020-12-16 10:03:15 所属栏目:安全 来源:网络整理
导读:我在捕获ClassCastException时遇到了一些问题. 它发生在检索函数的模式匹配的最后一种情况下,例外是不正确的. 我怎样才能解决这个问题? abstract class Property object EmptyProperty extends Property class PropertyCompanion[T] object Type extends Pr
|
我在捕获ClassCastException时遇到了一些问题.
它发生在检索函数的模式匹配的最后一种情况下,例外是不正确的. 我怎样才能解决这个问题? 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添加一个强制转换以获得正确的返回类型 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
