/**
* 父类向子类转换,新增数据,对象复制
* @param returnType 子类类型
* @param parent 父类对象
* @param <T> 转换结果
* @return
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
*/
public static <T> T pToC(Class<T> returnType,Object parent) throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor con=returnType.getDeclaredConstructor();
con.setAccessible(true);
T result= (T) con.newInstance();
return pToC(result,parent);
}
/**
* 父类向子类转换,融合数据
* @param result 子类对象
* @param parent 父类对象
* @param <T> 转换结果
* @return
* @throws IllegalAccessException
*/
public static <T> T pToC(T result,Object parent) throws IllegalAccessException{
if(parent.getClass().isAssignableFrom(result.getClass())){
Class parentClass=parent.getClass();
Field[] parentFields=parentClass.getDeclaredFields();
for(Field parentField:parentFields){
if(!Modifier.isFinal(parentField.getModifiers())){
parentField.setAccessible(true);
Object value=parentField.get(parent);
parentField.set(result,value);
}
}
}
return result;
}
转载注明地址:https://www.jianshu.com/p/cfb9b77d25f6
网友评论