Java Bean Components Java
In some cases it is not possible to compare all the fields of an object in equal() method of an object, for example in the cases of identity objects,
like the ones created with JPA @Entity. In those kind of cases if we want to check whether all fields for two instances of the same object have
same values or not, we can use
JavaBean component API
. The target class, of course, should follow the JavaBean component conventions. That will allow us to write a generic code to achieve the purpose rather than checking field values manually every time.
Following code shows how to achieve that.
public class BeanUtil {
public static <T> boolean haveSamePropertyValues (Class<T> type, T t1, T t2)
throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(type);
for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
Method m = pd.getReadMethod();
Object o1 = m.invoke(t1);
Object o2 = m.invoke(t2);
if (!Objects.equals(o1, o2)) {
return false;
}
}
return true;
}
}
Following is an example object to test above code:
public class Person {
private String id;
private String name;
private String address;
public Person (String id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public String getId () {
return id;
}
public void setId (String id) {
this.id = id;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getAddress () {
return address;
}
public void setAddress (String address) {
this.address = address;
}
@Override
public boolean equals (Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Person person = (Person) o;
return id != null ? id.equals(person.id) : person.id == null;
}
@Override
public int hashCode () {
return id != null ? id.hashCode() : 0;
}
}
public class Main {
public static void main (String[] args) throws Exception {
Person p1 = new Person("1", "Mike", "ABC");
Person p2 = new Person("1", "Julia", "XYZ");
Person p3 = new Person("1", "Mike", "ABC");
boolean b = BeanUtil.haveSamePropertyValues(Person.class, p1, p2);
System.out.println(b);
b = BeanUtil.haveSamePropertyValues(Person.class, p1, p3);
System.out.println(b);
}
} Outputfalse true
Example Project
Dependencies and Technologies Used:
|