解决方法
Apache Commons的
BeanComparator是你正在寻找的.
更新.将JavaBeans与一个属性进行比较的简单示例(比较只会产生一个属性,您应该创建与要匹配的属性一样多的BeanComparator).
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); } } } }
经过一些测试,一个结果是成功的.这是输出:
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
您需要将以下jar导入到项目中:commons-logging-version.jar,commons-beanutils-version.jar,commons-beanutils-core-version.jar,commons-beanutils-bean-collections-version.jar,commons -collections-version.jar.
这些文件包含在commons-logging,commons-beanutils和commons-collections API中.