I hava a model in Java 1.6 similar to this example:
public class Animal {
public String color;
}
public class Dog extends Animal {
public Float height;
}
public class Bird extends Animal {
public Integer wings;
}
Now I want cast from Animal to anyone child. I know that It's throw a runtime exception for forbidden cast. So I think that it's possible have a children only with the parent fields with the help of a constructor and java reflection. Example:
public class Animal {
public String color;
public Animal(Animal old){
//Set all fields by reflection. but how!
}
}
public class Dog extends Animal {
public Float height;
public Dog (Animal old){
super(old);
}
}
public class Bird extends Animal {
public Integer wings;
public Bird (Animal old){
super(old);
}
}
But how set all de parent fields with reflection?
SOLUTION BY Thinaesh (https://stackoverflow.com/a/17697270/1474638) Thanks!. I'm using Spring so only I need to do in the parent constructor the next:
public Animal(Animal old){
super();
BeanUtils.copyProperties(old, this);
}
public Dog(Animal old){
super(old);
}
public Bird(Animal old){
super(old);
}
Try BeanUtils.copyProperties from Apache commons library.(Same thing available in Spring's BeanUtils class.