如果A扩展B扩展C,我为什么不能转换为A,但得到一个ClassCastException铸造到C? [英] If A extends B extends C, why can I cast to A but get a ClassCastException casting to C?

查看:172
本文介绍了如果A扩展B扩展C,我为什么不能转换为A,但得到一个ClassCastException铸造到C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取使用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已经在这里修改的类层次结构,参见注释中的<一个href="http://www.netmite.com/android/mydroid/1.5/dalvik/libcore/security/src/main/java/org/bouncycastle/asn1/ASN1Sequence.java" rel="nofollow">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

这篇关于如果A扩展B扩展C,我为什么不能转换为A,但得到一个ClassCastException铸造到C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆