- commons-lang's EqualsBuilder.reflectionEquals(): uses reflections, isn't recursive (fields in nested objects aren't tested for equality), fields can be excluded.
- Unitil's ReflectionAssert: this one is recursive.
- convert the objects to Strings and compare those: implement .toString(), use common-lang's ToStringBuilder.reflectionToString or a JSON- or XML-Mapper. Most likely won't work with objects containing unordered Collections.
Compare Objects based on their Member Variables and Values
-
11-06-2023 - |
Вопрос
Can I use Apache BeanUtils to compare two objects and establish if they're equal (If they have the same member variables and values assigned to them)? If so, how? If not, is there an alternative library that I can use?
Something like:
public Boolean theSame(Object object1, Object object2) {
//If object1 member variables and values = object2 member variables and values:
return true;
}
Решение
Другие советы
Maybe you want to check on this [Comparator] (http://www.tutorialspoint.com/java/java_using_comparator.htm)
Override the .equals()
method in your class.
@Override
public boolean equals(Object object) {
//If object1 member variables and values = object2 member variables and values:
return true;
}
Note: You will need to override the hashCode()
method as well if you want to use the objects as a key in a HashMap
, HashTable
, or in a Set
.
Не связан с StackOverflow