Last active
December 15, 2015 09:43
-
-
Save twiceyuan/74ba2cfacec70734fd11 to your computer and use it in GitHub Desktop.
拷贝两个类中相同属性名的方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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