If A extends B extends C, why can I cast to A but get a ClassCastException casting to C?

孤人 提交于 2019-12-22 04:44:09

问题


I am trying to read an ASN1 object using Bouncycastle on Android. I expect it to be a DERSequence, which in Bouncycastle is a subclass of ASN1Sequence, which is a subclass of ASN1Object.

import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
...

ASN1InputStream ais = ...;
Object o = ais.readObject();
// Eclipse's debugger now says o is a DERSequence, as expected.

DERSequence o2 = (DERSequence)o;
ASN1Sequence o3 = o2;
ASN1Object o4 = o3;
// And o4 is now exactly what I want.

ASN1Object o5 = (ASN1Object)o;
// But this throws:
///    java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence

Based on feedback from the answers, I have constructed another, shorter example:

Object o = new DERSequence();
ASN1Object o1 = new DERSequence(); // This behaves fine.
ASN1Object o2 = (ASN1Object)o; // Throws ClassCastException.

What causes this cast to fail?


回答1:


Android has a modified class hierarchy here, see comment in http://www.netmite.com/android/mydroid/1.5/dalvik/libcore/security/src/main/java/org/bouncycastle/asn1/ASN1Sequence.java Are you absolutely sure the version you are using that a DERSequence is a subtype of ASN1Object?

e.g it is here http://www.eecs.berkeley.edu/~jonah/bc/org/bouncycastle/asn1/DERSequence.html

but not here http://www.androidjavadoc.com/m3-rc37a/org/bouncycastle/asn1/DERSequence.html




回答2:


Can you try executing this:

package classtest;

import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;

public class A {

    public static void main(String[] args) {
        testCast(new DERSequence());
    }

    private static void testCast(Object o) {
        DERSequence o2 = (DERSequence) o;
        ASN1Sequence o3 = o2;
        ASN1Object o4 = o3;

        ASN1Object o5 = (ASN1Object) o;
    }

}

(for me, this does not throw any exception)

If this does not work, you should check the answer of vickirk



来源:https://stackoverflow.com/questions/5634487/if-a-extends-b-extends-c-why-can-i-cast-to-a-but-get-a-classcastexception-casti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!