简体   繁体   English

继承类的Classcast异常

[英]Classcast exception for inherited classes

I have a class structure like this: 我有一个这样的类结构:

Interface A extends X
Class A_Impl implements A

Interface B extends A
Class B_Impl extends A_Impl implements B

My webservice client returns object of A and I need some parameters from B. So I do is this: 我的Web服务客户端返回A的对象,并且我需要B的一些参数。所以我这样做是:

A myA = (A) webservice.getA();
B myB = (B) myA;

But this always throws the ClassCast exception: 但这总是抛出ClassCast异常:

java.lang.ClassCastException: A_Impl cannot be cast to B

Am I doing something wrong here ? 我在这里做错什么了吗? How can I get some params from B class. 我如何从B类中获取一些参数。

You cannot get any properties of B when you have an instance of B 's supertype A , or any subtype of that other than B . 当您具有B的超类型A的实例或B以外的任何子类型时,将无法获得B任何属性。 For example, if you wanted to get the value of a field x that is a member of B , but your object is only an A , the field is not even present in the object. 例如,如果您想获取作为B成员的字段x的值,但您的对象只是A ,则该对象中甚至不存在该字段。 So what would the value of it be? 那么它的价值是什么? That is the reason you can't cast in this direction. 这就是您不能朝这个方向投掷的原因。 If you wan't to access the object like an instance of B , you have to change your webservice.getA() to something that actually returns a B (or a B_Impl ) 如果您不想像B的实例那样访问对象,则必须将webservice.getA()更改为实际上返回B (或B_Impl )。

If you have a reference to an object that doesn't implement B , there is no way to cast it to a B . 如果您引用的对象没有实现B ,则无法将其强制转换为B Full stop. 句号

Imagine if it was possible. 试想一下,如果这可能的。 Then what would this print? 那这个打印什么呢?

interface A {
    int getNumberOfLives();
}

interface B extends A {
    boolean isOrange();
}

class A_Impl implements A {
    int getNumberOfLives() {return 9;}
}

public class Main {
    public static void main(String[] args) {
        A a = getA();
        B b = (B)a;
        System.out.println(b.isOrange() ? "Is orange" : "Is not orange");
    }

    static A getA() {return new A_Impl();}
}

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

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