比较Java中不同类的对象字段 [英] Compare object fields of different classes in Java

查看:647
本文介绍了比较Java中不同类的对象字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象,每个对象有几十个字段:

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

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

Class2 {
    int propertyOne;
    String propertyTwo;
    ...
}

虽然某些字段名称不同,但它们应具有相同的含义和目的,例如 firstProperty propertyOne 。我想比较两个类的对象的相似字段实际上是否具有相同的值。
最优雅的方法是什么?

Although the some field are different in name, but they should have same meaning and purpose, for example firstProperty and propertyOne. I want to compare if the "similar" fields of objects of the two class actually have same values. What is the most elegant way to do this?

推荐答案

有两个类具有相似含义的字段,我会考虑声明一个接口

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;

    ...


}

界面,默认实现 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!

            ...;
    }
}

存在的风险isEqualTo 被覆盖 - 确保它永远不会发生。

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

这篇关于比较Java中不同类的对象字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆