Compare object fields of different classes in Java

后端 未结 3 2045
时光说笑
时光说笑 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.

    0 讨论(0)
  • 2021-01-23 21:59

    Comparing objects of different classes by specific fields is exactly the scenario that https://github.com/nejckorasa/compare-utils solves.

    Example:

    ObjectCmp.equalEqualityPairs(
        object1,
        object2,
        Arrays.asList(
            EqualityPair.of(o1 -> o1.getFirstProperty(), o2 -> o2.getPropertyOne()),
            EqualityPair.of(o1 -> o1.getSecondProperty(), o2 -> o2.getPropertyTwo())));
    

    Take a look, it might be useful!

    0 讨论(0)
  • 2021-01-23 22:00

    Having two classes with fields that have similar meanings, I'd consider declaring an interface.

    Class1 implements MyInterface {
        int firstProperty;
        String secondProperty;
        ...
        int getOne() {
            return firstProperty;
        }
        String getTwo() {
            return secondProperty;
        }
    
    }
    
    Class2 implements MyInterface {
        int propertyOne;
        String propertyTwo;
        ...
        int getOne() {
            return propertyOne;
        }
        String getTwo() {
            return propertyTwo;
    
        ...
    
    
    }
    

    And an interface with default implementation of isEqualTo:

    MyInterface {
        int getOne();
        String getTwo();
        ...
    
        boolean isEqualTo(MyInterface that) {
            return that != null &&
                this.getOne() == that.getOne() &&
                this.getTwo().equals(that.getTwo()) && //add null checks!
    
                ...;
        }
    }
    

    There is a risk of isEqualTo being overridden - make sure it never happens.

    0 讨论(0)
提交回复
热议问题