Thursday, April 17, 2014

Beanutils CopyUtil

import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.converters.DateConverter;
public class BeanPropertyCopyUtil {
        public static void copyProperties(Object src, Object dest, String... properties)
                    throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
         {
            DateConverter dtConverter = new DateConverter();
            dtConverter.setPattern("dd-MMM-yyyy");
            BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance();
            beanUtilsBean.getConvertUtils().register(dtConverter, java.util.Date.class);
           
                for (String property : properties) {
                        String[] arr = property.split(" ");
                        String srcProperty;
                        String destProperty;
                        if (arr.length == 2) {
                                srcProperty = arr[0];
                                destProperty = arr[1];
                        } else {
                                srcProperty = property;
                                destProperty = property;
                        }
                        String tmpStr = BeanUtils.getProperty(src, srcProperty).trim();
                        if(!tmpStr.equals("")){
                            //System.out.println("String is :" + tmpStr+":size:"+tmpStr.length() );
                            //BeanUtils.setProperty(dest, destProperty, BeanUtils.getProperty(src, srcProperty));
                            BeanUtils.setProperty(dest, destProperty, tmpStr);
                        }
                }
        } // end of method
}

No comments:

Post a Comment