Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.junit.Test;
- import java.beans.IntrospectionException;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.InvocationTargetException;
- public class DtoDiffTest {
- @Test
- public void DTO비교하기() throws IntrospectionException {
- ExtendedUser user1 = new ExtendedUser("이름1", "이메일1", 10);
- ExtendedUser user2 = new ExtendedUser("이름2", "이메일1", 20);
- diff(user1, user2, ExtendedUser.class);
- // result
- // age의 값이 다름. value1 : 10, value2 : 20
- // name의 값이 다름. value1 : 이름1, value2 : 이름2
- }
- public static <T> void diff(T target1, T target2, Class<T> targetClass) {
- try {
- for (PropertyDescriptor pd : Introspector.getBeanInfo(targetClass, Object.class).getPropertyDescriptors()) {
- Object value1 = pd.getReadMethod().invoke(target1);
- Object value2 = pd.getReadMethod().invoke(target2);
- boolean isNotEqualValue = !value1.equals(value2);
- if (isNotEqualValue) {
- System.out.println(String.format("%s의 값이 다름. value1 : %s, value2 : %s", pd.getName(), value1, value2));
- }
- }
- } catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
- throw new RuntimeException(e);
- }
- }
- public static class User {
- private String name;
- private String email;
- public User(String name, String email) {
- this.name = name;
- this.email = email;
- }
- // getter, setter
- }
- public static class ExtendedUser extends User {
- private int age;
- public ExtendedUser(String name, String email, int age) {
- super(name, email);
- this.age = age;
- }
- // getter, setter
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement