I'm trying to convert an object of unknown type to its unknown superclass at runtime. I figured the best way to do this is by using reflection but it doesn't seem to be having the desired effect. Here is an example block of code where Laptop extends Device:
Laptop obj1 = new Laptop();
System.out.println(obj1.getClass().getName());
String className = obj1.getClass().getSuperclass().getName();
System.out.println(className);
Object newObj;
try {
newObj = Class.forName(className).cast(obj1);
System.out.println(obj.getClass().getName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So here I expect to see the following printed to the console:
package.Library
package.Device
package.Device
But instead I'm getting:
package.Library
package.Device
package.Library
Which indicates to me that obj1 is not getting converted to its parent type Device as I would expect it too?
Could anyone let me know what it is that I'm doing wrong or if there is a better way to accomplish what I'm trying to do?
Aucun commentaire:
Enregistrer un commentaire