What is the best way to compare several javabean properties?

后端 未结 9 1834
礼貌的吻别
礼貌的吻别 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

    This is probably not too nice either, but it's far less evil (IMHO) than either of the two alternatives you've proposed.

    How about providing a single getter/setter pair that takes a numeric index field and then have getter/setter dereference the index field to the relevant member variable?

    i.e.:

    public class MyClass {
        public void setMember(int index, String value) {
            switch (index) {
               ...
            }
        }
    
        public String getMember(int index) {
            ...
        }
    
        static public String getMemberName(int index) {
            ...
        }
    }
    

    And then in your external class:

    public void compareAndUpdate(MyClass a, MyClass b) {
        for (int i = 0; i < a.getMemberCount(); ++i) {
            String sa = a.getMember();
            String sb = b.getMember();
            if (!sa.equals(sb)) {
                Log.v("compare", a.getMemberName(i));
                b.setMember(i, sa);
            }
        }
    }
    

    This at least allows you to keep all of the important logic in the class that's being examined.

提交回复
热议问题