有没有人知道一个免费的开源库(实用类),可以比较两个Java bean实例并返回在这两个实例中值不同的属性列表/数组?请发一个小例子。
谢谢
Tomas
Apache commons的BeanComparator是您正在寻找的。
更新。一个简单的示例,比较具有一个属性的JavaBeans(仅根据一个属性进行比较,您应该创建与要匹配的属性数量相同的BeanComparators)。
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
BeanComparator
可以用于集合排序。它是一个Comparator
实现,基于共享属性值比较bean。
BeanComparators
是通用比较器,可以作用于任何Java Bean。通过良好的底层bean反射系统,它们可以处理具有豆子属性、数组、集合和映射的bean。如果我们有一个
java.util.List
类型的Java Bean列表,其中类型为Person
- 其中Person
拥有一个年龄为一个Integer
,一个名字为一个字符串和一个国家为Country bean(Country bean本身有一个字符串名称),我们可以使用BeanComparator
按照需要对其进行排序。
List people = ...; // list of Person objects
//sort by age
BeanComparator comp = new BeanComparator("age");
Collections.sort(list, comp);
//sort by name
BeanComparator comp = new BeanComparator("name");
Collections.sort(list, comp);
//sort by country name
BeanComparator comp = new BeanComparator("country.name");
Collections.sort(list, comp);
PersonComparator
来进行排序。相反,一个单一的BeanComparator
类可以处理所有内容。
如果您正在实现比较器以动态比较属性(例如,考虑根据客户选择的列对Web页面上的行进行排序),那么您可以推迟构建比较器直到知道已选择哪个属性进行排序。
这就是
BeanComparator
真正发挥作用的地方。当您使用BeanComparator
时,通常编写的大量代码会被缩减为几行。