JavaBeans comparison
Does anyone know a free open source library (utility class) that allows you to compare two instances of a java bean and return a list / array of properties. The values in the two instances are different? Please post a small sample
Cheers, Thomas
Solution
The bean comparator of Apache Commons is what you are looking for
to update. A simple example of comparing JavaBeans with an attribute (the comparison will only produce one attribute, and you should create as many bean comparators as the attributes to match)
import org.apache.commons.beanutils.BeanComparator; public class TestBeanComparator { public TestBeanComparator() { } public class TestBean { int value; public TestBean() { } public int getValue() { return value; } public void setValue(int value) { this.value = value; } } public static void main(String[] args) { TestBeanComparator tbc = new TestBeanComparator(); tbc.go(); } public void go() { TestBean tbs [] = new TestBean[10]; for (int i = 0; i < tbs.length; i++) { tbs[i] = new TestBeanComparator.TestBean(); tbs[i].setValue((int) (Math.random() * 10)); System.out.println("TestBean["+i+"] = " + tbs[i].getValue()); } BeanComparator bc = new BeanComparator("value"); System.out.println(""); System.out.println("Value to match: " + tbs[0].getValue()); for (int i = 1; i < tbs.length; i++) { if(bc.compare(tbs[i],tbs[0]) == 0) { System.out.println("Match found in bean "+ i); } } } }
After some tests, one result is successful This is the output:
TestBean[0] = 0 TestBean[1] = 4 TestBean[2] = 0 TestBean[3] = 2 TestBean[4] = 7 TestBean[5] = 3 TestBean[6] = 0 TestBean[7] = 3 TestBean[8] = 7 TestBean[9] = 3 Value to match: 0 Match found in bean 2 Match found in bean 6
Obviously, increasing the size of the testbean array will increase the chance of obtaining a match
You need to import the following jar into the project: commons - logging - version jar,commons-beanutils-version. jar,commons-beanutils-core-version. jar,commons-beanutils-bean-collections-version. jar,commons -collections-version. jar.
These files are contained in the Commons logging, commons bean utils, and Commons collections APIs