PDA

View Full Version : BeanUtils.copyProperties(source, target) question



rharing
Jan 15th, 2005, 02:34 PM
Hi all,

small question (or request for change when deemed necessary). I use the BeanUtils.copyProperties method to populate a domain object from a form. The problem is that the form has properties for 3 specific domain objects, and thus when using BeanUtils.copyProperties method, I receive an error because not each object has all the properties. So while looking around, I saw that the BeanWrapperImpl throws an invalidPropertyException when a descriptor is missing. I understand why this is needed, but right now I can't use the copyProperties method. Is it possible to add another method that will catch the exception and just continue?

e.g.



/**
* Shameless rip of BeanUtils.copyProperties, but this method will catch the exceptions that are thrown when the
* descriptor's don't match in either bean, populating only those properties that are both present.
*
* Copy the property values of the given source bean into the given target bean,
* ignoring the given ignoreProperties.
* @param source the source bean
* @param target the target bean
* @param ignoreProperties array of property names to ignore
* @throws IllegalArgumentException if the classes of source and target do not match
*/
public static void copyProperties(Object source, Object target, String[] ignoreProperties)
throws IllegalArgumentException, BeansException {
if (source == null || target == null) {
throw new IllegalArgumentException("Source and target must not be null");
}
List ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;
BeanWrapper sourceBw = new BeanWrapperImpl(source);
BeanWrapper targetBw = new BeanWrapperImpl(target);
MutablePropertyValues values = new MutablePropertyValues();
for &#40;int i = 0; i < sourceBw.getPropertyDescriptors&#40;&#41;.length; i++&#41; &#123;
PropertyDescriptor sourceDesc = sourceBw.getPropertyDescriptors&#40;&#41;&#91;i&#93;;
String name = sourceDesc.getName&#40;&#41;;
PropertyDescriptor targetDesc = null;
try &#123;
targetDesc = targetBw.getPropertyDescriptor&#40;name&#41;;
&#125;
catch &#40;InvalidPropertyException e&#41; &#123;
continue;
&#125;
if &#40;targetDesc.getWriteMethod&#40;&#41; != null && targetDesc.getReadMethod&#40;&#41; != null &&
&#40;ignoreProperties == null || &#40;!ignoreList.contains&#40;name&#41;&#41;&#41;&#41; &#123;
values.addPropertyValue&#40;new PropertyValue&#40;name, sourceBw.getPropertyValue&#40;name&#41;&#41;&#41;;
&#125;
&#125;
targetBw.setPropertyValues&#40;values&#41;;
&#125;

Or should I use another class/method for this scenario?

Regards
Ronald

bpolka
Jan 15th, 2005, 04:50 PM
I use commons bean utils instead.