问题
It's easy to merge two simple, flat java beans using introspection:
BeanInfo info = Introspector.getBeanInfo( ContactBean.class );
PropertyDescriptor pDescArr[] = info.getPropertyDescriptors();
for(PropertyDescriptor pDesc : pDescArr){
//copy properties and check for conflicts here
}
However, it gets a little more complicated when the properties contain nested beans, or collections. Is there a smart tool somewhere which will handle a deep merge of complex beans?
Some more specifics on just how I'd like the merge to work:
Given a collection of source beans, and an empty target bean, simple properties should be copied over from the source to the target, unless there's a conflict. If there's a conflict, the field should be left empty. If a property is of a collection type, the values of the source beans should be combined, excluding duplicates, and copied to the destination property. These rules should apply recursively to properties which are beans themselves.
回答1:
Dozer or Smooks. Dozer is the winner if you just want bean merge. If you are looking for other usecases like csv to pojo etc then take a look at Smooks.
回答2:
You can use apache common beanutils. There is no built in method to do what you are trying to do, but you can use the helper methods in there to achieve the same
来源:https://stackoverflow.com/questions/4683687/tools-for-merging-java-beans