Comparing field values โ€‹โ€‹using reflection

I am trying to compare the field values โ€‹โ€‹of two different objects in a general way. I have a function (see below) that takes two objects and then gets the fields and then compares the fields in a loop and adds the fields to the list if they don't match - is this the right 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 # has a PropertyInfo class - is there something like this in Java? ALSO, is there a way to do something like f.getFieldValue() - I know there is no such method, but maybe there is another way.

+4
source share
2 answers

You can check org.apache.commons.lang.builder.EqualsBuilder, which will save you a lot of this problem if you want to make the field by comparing the fields.

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

If you want to compare the fields yourself, check out java.lang.Class.getDeclaredFields() , which will provide you with all the fields, including non-public fields.

Use f.get(qa).equals(f.get(qa4)) compare field values. Currently you are actually comparing field instances, not values.

+11
source

Libraries such as commons-beanutils can help you if you want to compare bean properties (values โ€‹โ€‹returned by getters) instead of comparing field values.

However, if you want to stick to simple reflection, you must:

  • Use Class.getDeclaredFields() instead of Class.getFields() , since the latter returns only public fields.
  • Since fields depend only on their class, you should cache the result and store the fields in the static / instance variable instead of calling getDeclaredFields() for each comparison.
  • Once you have an object of this class (say o ), to get the value of some field f for that particular object, you need to call: f.get(o) .
+3
source

Source: https://habr.com/ru/post/1447514/


All Articles