Scala:向下转型抛出 java.lang.ClassCastException
从非 Java 背景转向 Scala 给我带来了很多困难,包括这个。
scala> class A
defined class A
scala> class B extends A
defined class B
scala> val a = new A
a: A = A@2e893a4a
scala> val b = new B
b: B = B@3a47c130
scala> a.asInstanceOf[B]
java.lang.ClassCastException: A cannot be cast to B
...
scala> b.asInstanceOf[A]
res1: A = B@3a47c130
我知道抛出 ClassCastException 是因为在运行时, a
看起来不像 B,但事实上,它是(据我所知)。这是怎么回事?有什么解决方法吗?谢谢。
编辑:JVM 如何理解 a
无法转换为 B
?它是否在 a.getClass
和 B
之间执行一些浅层比较?
附注我试图将私有变量添加到库类中,并重写接受库中定义的类作为参数的类方法之一(我试图将字段添加到的类)。
Coming from a non-Java background to Scala has brought me a wide range of difficulties including this one.
scala> class A
defined class A
scala> class B extends A
defined class B
scala> val a = new A
a: A = A@2e893a4a
scala> val b = new B
b: B = B@3a47c130
scala> a.asInstanceOf[B]
java.lang.ClassCastException: A cannot be cast to B
...
scala> b.asInstanceOf[A]
res1: A = B@3a47c130
I understand that ClassCastException is thrown because at runtime, a
doesn't seem like a B but in fact, it is (as far as I understand). What's going on here? Any workarounds? Thanks.
Edit: how does the JVM understand that a
cannot be casted to B
? Does it perform some shallow comparison between a.getClass
and B
?
ps. I'm trying to add a private variable to a library class, and override one of the class methods that accepts a class defined in the library as argument (the class I'm trying to add the field to).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个向下的层次结构。 A 类是一个超类,B 类从它扩展而来,因此它更具体。你无法笼统地提升层次结构。这是一种设计选择,与子类型相关。
有没有一种语言可以提升层次结构?因为你似乎在暗示存在这样一种语言。
It's a hierarchy that goes down. Class A is a super class and B extends from it so it's more specific. You cannot go up the hierarchy in generalization. It's a design choice and relates to subtyping.
Is there any language where you can go up the hierarchy? Cause it seems like you're implying that there is such a language.
您不能将
A
转换为B
,只能反过来,因为 B 比 A 更具体。You cant cast
A
intoB
, only the other way around, because B is more specific than A.