user3663882
user3663882

Reputation: 7357

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. So I decided to write some sort of unit test which is ignored and won't run by 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. I would not want to override equals method just for testing purpose.

Is there a way to deal with it? Maybe there are some commons/guava libraries which can cope with that.

Upvotes: 0

Views: 992

Answers (1)

mm759
mm759

Reputation: 1424

You can use reflection to do it starting with YourClaas.class.getDeclaredFields(). Then you have to filter the returned fields, retrieve the values from the objects and do the comparison.

Upvotes: 2

Related Questions