Compare object fields of different classes in Java

后端 未结 3 2084
时光说笑
时光说笑 2021-01-23 21:02

I have two objects, each of which have tens of fields:

Class1 {
    int firstProperty;
    String secondProperty;
    ...
}

Class2 {
    int propertyOne;
    St         


        
3条回答
  •  误落风尘
    2021-01-23 21:36

    You are asking how to deal with the symptom of the disease - I would suggest to cure the root cause instead: by stepping back and refactor your classes completely.

    A class that has "tens" of fields is most likely violating the single responsibility principle.

    Don't ask yourself how to compare fields - ask yourself how you could design more classes with less fields that actually avoid having the same information in more than one place! You should (almost) always prefer a complex network of simple classes over a simple network of complex classes. Because the class is the root of your abstractions, and each class should only contain what is required to implement the one thing that class is about.

    Beyond that: there is no simple generic way that is also nice. You can of course write a utility class that compares objects using reflection - you simply give variable names and that utility code does generic comparisons. But is simple and generic - but not nice.

提交回复
热议问题