How to cast parent into child in Java
Well you could just do :
Parent p = new Child();
// do whatever
Child c = (Child)p;
Or if you have to start with a pure Parent object you could consider having a constructor in your parent class and calling :
class Child{
public Child(Parent p){
super(p);
}
}
class Parent{
public Parent(Args...){
//set params
}
}
Or the composition model :
class Child {
Parent p;
int param1;
int param2;
}
You can directly set the parent in that case.
You can also use Apache Commons BeanUtils to do this. Using its BeanUtils class you have access to a lot of utility methods for populating JavaBeans properties via reflection.
To copy all the common/inherited properties from a parent object to a child class object you can use its static copyProperties() method as:
BeanUtils.copyProperties(parentObj,childObject);
Note however that this is a heavy operation.