samedi 25 août 2018

Dynmically cast a object using reflection

Can someone explain why this code doesnt work and throw error:incompatible type :Object cannot be converted to 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:I'm talking about commented code





Aucun commentaire:

Enregistrer un commentaire