Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing field values using reflection

I am trying to compare the field values of two different objects in a generic way. I have a function (seen below) that takes in two Objects and then gets the fields and then compares the fields in a loop and adds the fields to a list if they are not the same - is this the proper way to do this?

public void compareFields(Object qa, Object qa4) throws FieldsNotEqualException
{

  Field[] qaFields = qa.getClass().getFields();
  Field[] qa4Fields = qa4.getClass().getFields();

  for(Field f:qaFields) 
  { 

    for(Field f4:qa4Fields)
    {
       if(f4.equals(f))
       {
           found = true;
           break;
       }
       else
       {
           continue;
       }
    }
  }

 if(!found)
 {
    report.add(/*some_formatted_string*/) //some global list 
    throw new FieldsNotEqualException();
 }
}

I was googling and I saw that C# had like a PropertyInfo Class - does Java have anything like that? ALSO, is there a way to do like f.getFieldValue() -I know there is no method like this but maybe there is another way???

like image 523
JonH Avatar asked Nov 21 '12 15:11

JonH


1 Answers

You might check out org.apache.commons.lang.builder.EqualsBuilder which will save you a lot of this hassle if you're wanting to do a field by field comparison.

org.apache.commons.lang.builder.EqualsBuilder.reflectionEquals(Object, Object)

If you're wanting to compare fields yourself, check out java.lang.Class.getDeclaredFields() which will give you all the fields including non-public fields.

To compare the value of the fields use f.get(qa).equals(f.get(qa4)) Currently, you are actually comparing the field instances and not the values.

like image 62
tjg184 Avatar answered Sep 22 '22 07:09

tjg184