I've got two objects of different classes that share some fields with the same name and type. These two objects are not related to each other. There's no possibility for me to create an interface or a parent class.
Now I want to compare those shared fields and as far as I know this should be possible using reflection.
These are the steps I've written for such a compare method:
Field[] inputFields = input.getClass().getDeclaredFields();
for (Field field : inputFields ) {
log.info(field.getName() + " : " + field.getType());
}
There will be an object called database
to which's fields the inputFields
are compared.
Unfortunately I don't know how to get the value of my fields. Do you have some hints for me?
Ok, with field.get(input)
I've got the value now, but maybe I was wrong and that's not what I need.
Actually, I want to compare this field with another one, so I need to call the equals method on this field. But at first I've got to cast it to it's appropriate class.
So is there something like ((field.getClass()) field).equals(...)
that would work?
Here is a Solution to this problem, a utility class called
FieldHelper
that has a methodThe returned map has the field name as key and an array of the two field values as value:
Test Code:
Output:
Note: this code doesn't actually read the fields, it follows the java bean convention and uses the getters instead. It would be easy to rewrite it to use fields, but I would advise against it.
I think you're looking for
Field.get()
:Check dedicated chapter of Sun's Java tutorial. This page answers your particular question with example.