jeudi 17 octobre 2019

Compare two objects properties generically using reflection

I am trying to build a function that receives two objects (from type Object) that inspects their fields and retrieves the fields that has different values (a comparison on field level).

The idea i have is that i get all fields, setting them accessible and comparing values:

Field[] fields = item.getClass().getFields();
Class clazz = item.getClass();
for (Field field : fields) {
    field.setAccessible(true);
    if (!field.get(item).toString().equals(field.get(target).toString())) {
        System.out.println("detected a difference.");
    }
}

I am not sure if this is the best way to do this, specially that we are forcing fields to be accessible.

Can you recommend better ways ?





Aucun commentaire:

Enregistrer un commentaire