简体   繁体   English

如何通过字段比较两个对象?

[英]How to compare two objects by their fields?

I have pretty large number of classes which are Serializable / Externalizable and unfortunately it happens quite often that I forget to serailize/desirialize a new field when adding it to a class or mispell readObject instead of readDouble . 我有大量可Serializable /可Externalizable Serializable的类,但是不幸的是,经常发生的事情是,我忘记将新字段添加到类中或拼写readObject而不是readDouble时,会对其Serializable /反Serializable So I decided to write some sort of unit test which is ignored and won't run by maven-surefire-plugin . 因此,我决定编写某种单元测试,该单元测试将被maven-surefire-plugin忽略并且不会运行。 It's only for my own needs. 只是为了我自己的需要。 It looks like this: 看起来像这样:

@Test(enabled = false)
public void testEquality(Object o){
    String oPart = o.toString();
    try (FileOutputStream fos = new FileOutputStream("/home/myusr/testser/" + oPart);
         ObjectOutputStream ous = new ObjectOutputStream(fos)) {
        ous.writeObject(o);
    } catch (FileNotFoundException | IOException e) {
        e.printStackTrace();
    }
    Object oo = null;
    try (FileInputStream fis = new FileInputStream("/home/myusr/testser/" + oPart);
         ObjectInputStream ois = new ObjectInputStream(fis)) {
        Object oo =  ois.readObject();
    } catch (FileNotFoundException | IOException | ClassNotFoundException e) {
        e.printStackTrace();
    } 
    // Need to compare all non-transient fields of o and oo
}

But the question is how to compare all fields which are not transient with the same name. 但是问题是如何比较所有具有相同名称的非transient字段。 I would not want to override equals method just for testing purpose. 我不想仅出于测试目的而覆盖equals方法。

Is there a way to deal with it? 有办法解决吗? Maybe there are some commons / guava libraries which can cope with that. 也许有一些commons / guava库可以解决这个问题。

You can use reflection to do it starting with YourClaas.class.getDeclaredFields() . 您可以使用反射从YourClaas.class.getDeclaredFields()开始进行YourClaas.class.getDeclaredFields() Then you have to filter the returned fields, retrieve the values from the objects and do the comparison. 然后,您必须过滤返回的字段,从对象中检索值并进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM