compare Two Java Beans - Java Reflection

Java examples for Reflection:Java Bean

Description

compare Two Java Beans

Demo Code


//package com.java2s;
import java.lang.reflect.Method;
import java.util.Arrays;

public class Main {


    public static boolean compareTwoBeans(Object o1, Object o2) {
        if (o1 == o2) {
            return true;
        }/* w  ww. j  a v a2 s.c  om*/
        if (o1 == null || o2 == null) { // from statement above, we know both aren't null.
            return false;
        }
        for (Method method0 : o1.getClass().getMethods()) {
            final String methodName = method0.getName();
            if ((methodName.startsWith("get") || methodName
                    .startsWith("is"))
                    && method0.getParameterTypes().length == 0
                    && methodName != "getClass") {
                try {
                    Method method1 = o2.getClass().getMethod(methodName,
                            (Class[]) null);
                    Object value1 = method0.invoke(o1, (Object[]) null);
                    Object value2 = method1.invoke(o2, (Object[]) null);
                    if (value1 == null) {
                        return value1 == value2; // both are null and therefore equal.
                    }
                    // handle byte arrays[]
                    if (method0.getReturnType() == byte[].class) {
                        return Arrays.equals((byte[]) value1,
                                (byte[]) value2);
                    }

                    if (!value1.equals(value2)) {
                        return false;
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return true;
    }
}

Related Tutorials