What is the best way to compare several javabean properties?

后端 未结 9 1817
礼貌的吻别
礼貌的吻别 2020-12-14 03:26

I need to compare dozens of fields in two objects (instances of the same class), and do some logging and updating in case there are differences. Meta code could look somethi

9条回答
  •  隐瞒了意图╮
    2020-12-14 04:03

    The JavaBeans API is intended to help with introspection. It has been around in one form or another since Java version 1.2 and has been pretty usable since version 1.4.

    Demo code that compares a list of properties in two beans:

      public static void compareBeans(PrintStream log,
          Object bean1, Object bean2, String... propertyNames)
          throws IntrospectionException,
          IllegalAccessException, InvocationTargetException {
        Set names = new HashSet(Arrays
            .asList(propertyNames));
        BeanInfo beanInfo = Introspector.getBeanInfo(bean1
            .getClass());
        for (PropertyDescriptor prop : beanInfo
            .getPropertyDescriptors()) {
          if (names.remove(prop.getName())) {
            Method getter = prop.getReadMethod();
            Object value1 = getter.invoke(bean1);
            Object value2 = getter.invoke(bean2);
            if (value1 == value2
                || (value1 != null && value1.equals(value2))) {
              continue;
            }
            log.format("%s: %s is different than %s%n", prop
                .getName(), "" + value1, "" + value2);
            Method setter = prop.getWriteMethod();
            setter.invoke(bean2, value2);
          }
        }
        if (names.size() > 0) {
          throw new IllegalArgumentException("" + names);
        }
      }
    

    Sample invocation:

    compareBeans(System.out, bean1, bean2, "foo", "bar");
    

    If you go the annotations route, consider dumping reflection and generating the comparison code with a compile-time annotation processor or some other code generator.

提交回复
热议问题