我在 Java 1.6 中有一个类似于这个例子的模型:
public class Animal {
public String color;
}
public class Dog extends Animal {
public Float height;
}
public class Bird extends Animal {
public Integer wings;
}
现在我想从 Animal 转换到任何孩子。我知道它会为禁止的演员抛出运行时异常。所以我认为在构造函数和java反射的帮助下,只有父字段才有可能有一个孩子。例子:
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);
}
}
但是如何用反射设置所有的父字段呢?
Thinaesh 的解决方案(https://stackoverflow.com/a/17697270/1474638)谢谢!我正在使用 Spring,所以只需要在父构造函数中执行以下操作:
public Animal(Animal old){
super();
BeanUtils.copyProperties(old, this);
}
public Dog(Animal old){
super(old);
}
public Bird(Animal old){
super(old);
}