Skip to content

Instantly share code, notes, and snippets.

@twiceyuan
Last active December 15, 2015 09:43
Show Gist options
  • Save twiceyuan/74ba2cfacec70734fd11 to your computer and use it in GitHub Desktop.
Save twiceyuan/74ba2cfacec70734fd11 to your computer and use it in GitHub Desktop.
拷贝两个类中相同属性名的方法
public static void copy(Object from, Object to) {
Field[] fromFields = from.getClass().getDeclaredFields();
Field[] toFields = to.getClass().getDeclaredFields();
Class toClass = to.getClass();
Set<String> toFieldSet = Stream.of(toFields).map(Field::getName).collect(Collectors.toSet());
for (Field fromField : fromFields) {
// 判断来源属性中是否含有目标属性
if (toFieldSet.contains(fromField.getName())) {
try {
Field toField = toClass.getDeclaredField(fromField.getName());
toField.set(to, fromField.get(from));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment