BeanUtil解读

来源:互联网 发布:安全电脑炒股软件 编辑:程序博客网 时间:2024/05/21 15:43
package com.sand.mis.util;import java.beans.PropertyDescriptor;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Modifier;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import org.apache.log4j.Logger;import org.springframework.beans.BeanUtils;import org.springframework.beans.BeansException;import org.springframework.beans.FatalBeanException;import org.springframework.util.Assert;import com.sand.mis.base.BaseException;import com.sand.mis.entity.BmAccount;public class BeanUtil extends BeanUtils {/** * 日志操作类 */    private static Logger logger = Logger.getLogger(BeanUtils.class);    private static final List<String> ignoreProsInMis =new ArrayList<String>();static{ignoreProsInMis.add("id");ignoreProsInMis.add("createUser");ignoreProsInMis.add("createTime");}public static void copyProperties(Object source, Object target) throws BeansException {copyPros(source, target, null);}public static void copyProperties(Object source, Object target, String ignoreProperties[]) throws BeansException {copyPros(source, target, ignoreProperties);}/** *  * @Title: copyPros * @param source * @param target * @param ignoreProperties * @throws BeansException * @return void */@SuppressWarnings("rawtypes")private static void copyPros(Object source, Object target, String ignoreProperties[]) throws BeansException {Assert.notNull(source, "Source must not be null");Assert.notNull(target, "Target must not be null");Class actualEditable = target.getClass();PropertyDescriptor targetPds[] = getPropertyDescriptors(actualEditable);//目标类的属性// add ignoreProperties only for misif (ignoreProperties != null) {ignoreProsInMis.addAll(Arrays.asList(ignoreProperties));}for (int i = 0; i < targetPds.length; i++) {PropertyDescriptor targetPd = targetPds[i];if (targetPd.getWriteMethod() == null || ignoreProsInMis.contains(targetPd.getName()))//如果在忽略的数组中,不执行本字段的copycontinue;// when bean is copied in mis,it needn't copy setif (Set.class.getName().equals(targetPd.getPropertyType().getName()))//如果字段是set类型的话,跳过continue;PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());if (sourcePd == null || sourcePd.getReadMethod() == null)//如果source中不存在该字段,跳过continue;try {Method readMethod = sourcePd.getReadMethod();if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()))//如果该字段可读readMethod.setAccessible(true);Object value = readMethod.invoke(source, new Object[0]);Method writeMethod = targetPd.getWriteMethod();if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()))//如果该字段可写writeMethod.setAccessible(true);writeMethod.invoke(target, new Object[] { value });//赋值} catch (Throwable ex) {throw new FatalBeanException("Could not copy properties from source to target", ex);}}}/** * List element must implement java.io.Serializable * */@SuppressWarnings("rawtypes")public static Object deepCopy(Object obj) throws IOException, ClassNotFoundException, BaseException {    if(obj==null){    return null;    }ByteArrayOutputStream byteOut = new ByteArrayOutputStream();   ObjectOutputStream out = new ObjectOutputStream(byteOut);   out.writeObject(obj);   ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());   ObjectInputStream in =new ObjectInputStream(byteIn);   List dest = (List)in.readObject();in.close();byteIn.close();out.close();byteOut.close();        return dest;       } /**     * 比较两个BEAN或MAP对象的值是否相等      * 如果是BEAN与MAP对象比较时MAP中的key值应与BEAN的属性值名称相同且字段数目要一致     * @param source     * @param target     * @return     */    public static boolean beanEquals(Object source, Object target) {        if (source == null || target == null) {            return false;        }        boolean rv = true;        if (source instanceof Map) {            rv = mapOfSrc(source, target, rv);//source是map        } else {            rv = classOfSrc(source, target, rv);//source是类        }        logger.info("THE EQUALS RESULT IS " + rv);        return rv;    }    /**     * 源目标为MAP类型时     * @param source     * @param target     * @param rv     * @return     */    @SuppressWarnings({ "unchecked", "rawtypes" })private static boolean mapOfSrc(Object source, Object target, boolean rv) {        HashMap<String, String> map = new HashMap<String, String>();        map = (HashMap) source;        for (String key : map.keySet()) {            if (target instanceof Map) {                HashMap<String, String> tarMap = new HashMap<String, String>();                tarMap = (HashMap) target;                if(tarMap.get(key)==null){                    rv = false;                    break;                }                if (!map.get(key).equals(tarMap.get(key))) {                    rv = false;                    break;                }            } else {                String tarValue = getClassValue(target, key) == null ? "" : getClassValue(target, key).toString();                if (!tarValue.equals(map.get(key))) {                    rv = false;                    break;                }            }        }        return rv;    }    /**     * 源目标为非MAP类型时     * @param source     * @param target     * @param rv     * @return     */    @SuppressWarnings({ "unchecked", "rawtypes" })private static boolean classOfSrc(Object source, Object target, boolean rv) {        Class<?> srcClass = source.getClass();        Field[] fields = srcClass.getDeclaredFields();//source        for (Field field : fields) {            String nameKey = field.getName();            if (target instanceof Map) {                HashMap<String, String> tarMap = new HashMap<String, String>();                tarMap = (HashMap) target;                String srcValue = getClassValue(source, nameKey) == null ? "" : getClassValue(source, nameKey)                        .toString();                if(tarMap.get(nameKey)==null){                    rv = false;                    break;                }                if (!tarMap.get(nameKey).equals(srcValue)) {                    rv = false;                    break;                }            } else {                String srcValue = getClassValue(source, nameKey) == null ? "" : getClassValue(source, nameKey)                        .toString();                String tarValue = getClassValue(target, nameKey) == null ? "" : getClassValue(target, nameKey)                        .toString();                if (!srcValue.equals(tarValue)) {                    rv = false;                    break;                }            }        }        return rv;    }    /**     * 根据字段名称取值     * @param obj     * @param fieldName     * @return     */    @SuppressWarnings("rawtypes")public static Object getClassValue(Object obj, String fieldName) {        if (obj == null) {            return null;        }        try {            Class beanClass = obj.getClass();            Method[] ms = beanClass.getMethods();            for (int i = 0; i < ms.length; i++) {                // 非get方法不取                if (!ms[i].getName().startsWith("get")) {                    continue;                }                Object objValue = null;                try {                    objValue = ms[i].invoke(obj, new Object[] {});                } catch (Exception e) {                     logger.info("反射取值出错:" + e.toString());                    continue;                }                if (objValue == null) {                    continue;                }                if (ms[i].getName().toUpperCase().equals(fieldName.toUpperCase())                        || ms[i].getName().substring(3).toUpperCase().equals(fieldName.toUpperCase())) {                    return objValue;                } else if (fieldName.toUpperCase().equals("SID")                        && (ms[i].getName().toUpperCase().equals("ID") || ms[i].getName().substring(3).toUpperCase()                                .equals("ID"))) {                    return objValue;                }            }        } catch (Exception e) {            // logger.info("取方法出错!" + e.toString());        }        return null;    }        public static void main(String args[]) {    BmAccount bmAccount = new BmAccount();bmAccount.setAccount("123");bmAccount.setAccountBank("test");BmAccount bmAccount1 = new BmAccount();bmAccount1.setAccount("123");bmAccount1.setAccountBank("test");//boolean isEqual = bmAccount1.equals(bmAccount);boolean isEqual = beanEquals(bmAccount1, bmAccount); System.out.println("bmAccount与bmAccount1的比较结果是:"+isEqual);System.out.println("bmAccount与bmAccount1的比较结果是:"+ (bmAccount1 == bmAccount));    }}