Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import org.junit.Test;
  2.  
  3. import java.beans.IntrospectionException;
  4. import java.beans.Introspector;
  5. import java.beans.PropertyDescriptor;
  6. import java.lang.reflect.InvocationTargetException;
  7.  
  8. public class DtoDiffTest {
  9.  
  10. @Test
  11. public void DTO비교하기() throws IntrospectionException {
  12. ExtendedUser user1 = new ExtendedUser("이름1", "이메일1", 10);
  13. ExtendedUser user2 = new ExtendedUser("이름2", "이메일1", 20);
  14.  
  15. diff(user1, user2, ExtendedUser.class);
  16. // result
  17. // age의 값이 다름. value1 : 10, value2 : 20
  18. // name의 값이 다름. value1 : 이름1, value2 : 이름2
  19. }
  20.  
  21. public static <T> void diff(T target1, T target2, Class<T> targetClass) {
  22. try {
  23. for (PropertyDescriptor pd : Introspector.getBeanInfo(targetClass, Object.class).getPropertyDescriptors()) {
  24. Object value1 = pd.getReadMethod().invoke(target1);
  25. Object value2 = pd.getReadMethod().invoke(target2);
  26.  
  27. boolean isNotEqualValue = !value1.equals(value2);
  28. if (isNotEqualValue) {
  29. System.out.println(String.format("%s의 값이 다름. value1 : %s, value2 : %s", pd.getName(), value1, value2));
  30. }
  31. }
  32. } catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
  33. throw new RuntimeException(e);
  34. }
  35. }
  36.  
  37. public static class User {
  38. private String name;
  39. private String email;
  40.  
  41. public User(String name, String email) {
  42. this.name = name;
  43. this.email = email;
  44. }
  45.  
  46. // getter, setter
  47. }
  48.  
  49.  
  50. public static class ExtendedUser extends User {
  51. private int age;
  52.  
  53. public ExtendedUser(String name, String email, int age) {
  54. super(name, email);
  55. this.age = age;
  56. }
  57. // getter, setter
  58. }
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement