有人可以解释为什么此代码不起作用并引发错误:类型不兼容:对象无法转换为aaa
class aaa {}
class bbb extends aaa {
}
class psp {
public static void main(String args[]) {
bbb b = new bbb();
Object object = b;
Class clazz = aaa.class;
//aaa a=clazz.cast(b); doesnot work
//aaa a=Class.forName("aaa").cast(object); doesnt work
//aaa a=Class.forName("aaa").cast(b);doesnt work
aaa a = (aaa) object;
a = (aaa) aa;
a = aaa.class.cast(b);
}
}
PS:我说的是注释代码
答案 0 :(得分:0)
有两个容易解决的问题:
将clazz
声明为Class<aaa>
,以消除将clazz.cast(b)
强制转换为aaa
的需要:
Class<aaa> clazz = aaa.class;
aaa a = clazz.cast(b); //works
Class.forName
返回Class<?>
,因此您需要显式强制转换:
aaa a1 = (aaa) Class.forName("aaa").cast(object);
aaa a2 = (aaa) Class.forName("aaa").cast(b);