如果A扩展B扩展C,我为什么不能转换为A,但得到一个ClassCastException铸造到C?我为、转换为、ClassCastException

2023-09-04 11:32:26 作者:凉辰梦瑾°

我想读取使用BouncyCastle的在Android上的ASN1对象。我希望它是一个DERSequence,这在BouncyCastle的一个子类ASN1Sequence,这是ASN1Object的子类。

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?

推荐答案

Android已经在这里修改的类层次结构,参见注释中的http://www.netmite.com/android/mydroid/1.5/dalvik/libcore/security/src/main/java/org/bouncycastle/asn1/ASN1Sequence.java你真的确认您使用的是一个DERSequence是ASN1Object的子类型?版本

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?

例如,它是在这里 HTTP:// WWW .eecs.berkeley.edu /〜约拿/ BC /组织/ BouncyCastle的/ ASN 1 / DERSequence.html

但不是在这里 http://www.androidjavadoc.com /m3-rc37a/org/bouncycastle/asn1/DERSequence.html