集册 Java实例教程 比较两个Java Bean

比较两个Java Bean

欢马劈雪     最近更新时间:2020-01-02 10:19:05

435
比较两个Java Bean


//package com.nowjava;

import java.lang.reflect.Method;/** 来 自 nowjava - 时代Java**/

import java.util.Arrays;


public class Main {



    public static boolean compareTwoBeans(Object o1, Object o2) {

        if (o1 == o2) {

            return true;

        }

        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"))/** 来自 n o w j a v a . c o m - 时  代  Java**/

                    && 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);

                    }


                    
展开阅读全文