使用反射动态投射对象

时间:2018-08-26 05:14:20

标签: java reflection

有人可以解释为什么此代码不起作用并引发错误:类型不兼容:对象无法转换为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:我说的是注释代码

1 个答案:

答案 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);