一、子类的实列化通过父类实现。(代码正常)
二、基于子类的实列化是通过父类实现,强制转换父类。(代码正常)
三、父类的实列化不能强制转换为子类。(代码错误,提示:java.lang.ClassCastException)
针对第三种情况,建议采用方案,将父类属性值全部拷贝至子类实列中。
/**
* 父类 属性值拷贝至 子类中
* @param father
* @param child
* @throws Exception
*/
public static <T>void fatherToChild(T father,T child) throws Exception {
if (child.getClass().getSuperclass()!=father.getClass()){
throw new Exception("child 不是 father 的子类");
}
Class<?> fatherClass = father.getClass();
Field[] declaredFields = fatherClass.getDeclaredFields();
for (int i = 0; i < declaredFields.length; i++) {
Field field=declaredFields[i];
Method method=fatherClass.getDeclaredMethod("get"+StringUtils.capitalize(field.getName()));
Object obj = method.invoke(father);
field.setAccessible(true);
field.set(child,obj);
}
}