Java通过反射拷贝值给另一个实体类
作者:
你的益达233 | 来源:发表于
2022-07-18 14:41 被阅读0次直接上代码
public void copy(Object source, Object dest) throws Exception {
// 获取属性
Field[] sourceProperty = source.getClass().getDeclaredFields();
Field[] destProperty = dest.getClass().getDeclaredFields();
try {
for (int i = 0; i < sourceProperty.length; i++) {
for (int j = 0; j < destProperty.length; j++) {
if (sourceProperty[i].getName().equals(destProperty[j].getName())) {
destProperty[j].setAccessible(true);
sourceProperty[i].setAccessible(true);
destProperty[j].set(dest,sourceProperty[i].get(source));
break;
}
}
}
} catch (Exception e) {
throw new Exception("属性复制出错:" + e.getMessage());
}
}
本文标题:Java通过反射拷贝值给另一个实体类
本文链接:https://www.haomeiwen.com/subject/sjqdirtx.html
网友评论