What is the best way to compare several javabean properties?

后端 未结 9 1830
礼貌的吻别
礼貌的吻别 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 03:50

    Use Annotations.

    If you mark the fields that you need to compare (no matter if they are private, you still don't lose the encapsulation, and then get those fields and compare them. It could be as follows:

    In the Class that need to be compared:

    @ComparableField 
    private String field1;
    
    @ComparableField
    private String field2;
    
    private String field_nocomparable;
    

    And in the external class:

    public  void compare(T t, T t2) throws IllegalArgumentException,
                                              IllegalAccessException {
        Field[] fields = t.getClass().getDeclaredFields();
        if (fields != null) {
            for (Field field : fields) {
                if (field.isAnnotationPresent(ComparableField.class)) {
                    field.setAccessible(true);
                    if ( (field.get(t)).equals(field.get(t2)) )
                        System.out.println("equals");
                    field.setAccessible(false);
                }
            }
        }
    }
    

    The code is not tested, but let me know if helps.

提交回复
热议问题