Compare object fields of different classes in Java

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

提交回复
热议问题