`

java中两个对象间的属性值复制,比较,转为map方法实现

    博客分类:
  • JAVA
阅读更多
复制代码
package com.franson.study.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.avalon.framework.service.ServiceException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BeanUtil {

    private static Log log = LogFactory.getLog(BeanUtil.class);

    /**
     * 两对象之间的拷贝(在目标对象中存在的所有set方法,如果在源对象中存在对应的get方法,不管源对象的get方法的返回值是否为null,都进行拷贝)
     * 仅拷贝方法名及方法返回类型完全一样的属性值
     * @param desc     目标对象
     * @param orig     源对象
     * @param excludeFields 不拷贝的field(多个用逗号隔开)
     */
    public static void copyPropertiesNotForce(Object desc, Object orig,String excludeFields) {
        copyPropertiesNotForce(desc, orig, excludeFields, true);
    }
    /**
     * 两对象之间的拷贝(在目标对象中存在的所有set方法,如果在源对象中存在对应的get方法,不管源对象的get方法的返回值是否为null,都进行拷贝)
     * 仅拷贝方法名及方法返回类型完全一样的属性值
     * @param desc     目标对象
     * @param orig     源对象
     * @param excludeFields     源对象
     * @param isCopyNull     为null的属性是否拷贝(true拷贝null属性;false不拷贝null属性)
     * @param excludeFields 不拷贝的field(多个用逗号隔开)
     */
    public static void copyPropertiesNotForce(Object desc, Object orig,String excludeFields, boolean isCopyNull) {
        Class<?> origClass = orig.getClass();
        Class<?> descClass = desc.getClass();

        Method[] descMethods = descClass.getMethods();
        Method[] origMethods = origClass.getMethods();

        boolean needExclude = false;                    //是否需要过滤部分字段
        if(!StringUtil.isEmpty(excludeFields)){
            needExclude = true;
            excludeFields = "," + excludeFields.toLowerCase() + ",";
        }
        
        Map<String,Method> methodMap = new HashMap<String,Method>();
        for (int i = 0; i < origMethods.length; i++) {
            Method method = origMethods[i];
            String methodName = method.getName();
            if (!methodName.equals("getClass")
                    && methodName.startsWith("get")
                    && (method.getParameterTypes() == null || method
                            .getParameterTypes().length == 0)) {
                if(needExclude && excludeFields.indexOf(methodName.substring(3).toLowerCase()) > -1){
                    continue;
                }
                methodMap.put(methodName, method);
            }
        }
        for (int i = 0; i < descMethods.length; i++) {
            Method method = descMethods[i];
            String methodName = method.getName();
            if (!methodName.equals("getClass")
                    && methodName.startsWith("get")
                    && (method.getParameterTypes() == null || method
                            .getParameterTypes().length == 0)) {
                if (methodMap.containsKey(methodName)) {
                    Method origMethod = (Method) methodMap.get(methodName);
                    try {
                        if (method.getReturnType().equals(
                                origMethod.getReturnType())) {
                            Object returnObj = origMethod.invoke(orig, null);
                            if(!isCopyNull && returnObj == null){
                                continue;
                            }
                            
                            String field = methodName.substring(3);
                            String setMethodName = "set" + field;
                            Method setMethod = descClass.getMethod(
                                    setMethodName, new Class[] { method
                                            .getReturnType() });
                            setMethod.invoke(desc, new Object[] { returnObj });
                        }
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    /**
     * 两对象之间的拷贝(在目标对象中存在的所有set方法,如果在源对象中存在对应的get方法,不管源对象的get方法的返回值是否为null,都进行拷贝)
     * 仅拷贝方法名及方法返回类型完全一样的属性值
     * @param desc     目标对象
     * @param orig     源对象
     */
    public static void copyPropertiesNotForce(Object desc, Object orig) {
        copyPropertiesNotForce(desc, orig, null);
    }
    
    /**
     * 两对象之间的拷贝(在目标对象中存在的所有set方法,如果在源对象中存在对应的get方法,源对象的get方法的返回值为null的不拷贝)
     * 仅拷贝方法名及方法返回类型完全一样的属性值
     * @param desc     目标对象
     * @param orig     源对象
     * @param excludeFields 不拷贝的field(多个用逗号隔开)
     */
    public static void copyPropertiesNotNull(Object desc, Object orig) {
        copyPropertiesNotForce(desc, orig, null, false);
    }
    
    public static void copyPropertiesNotNull(Object desc, Object orig,String excludeFields) {
        copyPropertiesNotForce(desc, orig, excludeFields, false);
    }
    /**
     * 判断两个对象的所有相同属性值是否相等,注意尽是比较相同的属性,对于A对象属性比B对象属性多,如果相同属性值相同,则返回为true
     * @param desc
     * @param orig
     * @return 相等返回true,否则返回false
     * @throws CrmBaseException
     */
public static boolean isEqualBeanProperties(Object desc, Object orig) throws CrmBaseException {
        String result= compareBeanProperties(desc,orig);
        if(result.equals("[]"))
            return true;
        return false;
}
    /**
     * 比较两个Bean相同字段的值(以源对象的值为基准,json串中显示目标对象中的值)【仅比较可转换为string的类型】
     * @param desc 目标对象
     * @param orig 源对象        
     * @return String 不一致的字段json串
     * @throws  ServiceException
     */
    public static String compareBeanProperties(Object desc, Object orig)
            throws CrmBaseException {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> origClass = orig.getClass();
        Class<?> descClass = desc.getClass();

        Method[] descMethods = descClass.getMethods();
        Method[] origMethods = origClass.getMethods();

        Map<String,Method> methodMap = new HashMap<String,Method>();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < origMethods.length; i++) {
            Method method = origMethods[i];
            String methodName = method.getName();
            if (!methodName.equals("getClass")
                    && methodName.startsWith("get")
                    && (method.getParameterTypes() == null || method
                            .getParameterTypes().length == 0)) {
                methodMap.put(methodName, method);
            }
        }
        for (int i = 0; i < descMethods.length; i++) {
            Method method = descMethods[i];
            String methodName = method.getName();
            if (!methodName.equals("getClass")
                    && methodName.startsWith("get")
                    && (method.getParameterTypes() == null || method
                            .getParameterTypes().length == 0)) {
                if (methodMap.containsKey(methodName)) {
                    Method origMethod = (Method) methodMap.get(methodName);
                    try {
                        if (method.getReturnType().equals(
                                origMethod.getReturnType())) {
                            Object origObj = origMethod.invoke(orig, null);
                            origObj = origObj == null ? "" : origObj;

                            Method descMethod = descClass.getMethod(methodName,
                                    null);
                            Object descObj = descMethod.invoke(desc, null);
                            descObj = descObj == null ? "" : descObj;

                            if (!origObj.equals(descObj)) {
                                map.put(methodName.substring(3), descObj);
                                sb.append(",{'field':'");
                                sb.append(methodName.substring(3));
                                sb.append("','msg':'");
                                sb.append(descObj.toString().replaceAll("\'",
                                        ""));
                                sb.append("'}");
                            }
                        }
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        String str = "[";
        if (sb.length() > 0) {
            str += sb.substring(1);
        }
        return str + "]";
    }

    /**
     * bean转Map
     * @param bean
     * @return
     */
    public static Map beanToMap(Object bean){
         //return bean2Map(bean);
        return objectToMap(bean);
    }

      
    /**
     * 通过字段名获取方法数组
     * @param beanClass            Class<?>
     * @param fieldNameArray    要输出的所有字段名数组
     * @return                Method[]
     */
    public static Method[] getMethods(Class<?> beanClass,String[] fieldNameArray){
        Method[] methodArray = new Method[fieldNameArray.length];
        
        String methodName;
        String fieldName;
        for (int i=0;i<fieldNameArray.length;i++) {
            Method method = null;
            fieldName = fieldNameArray[i];
            methodName = fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
            try {
                method = beanClass.getMethod("get"+methodName, null);
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                try {
                    method = beanClass.getMethod("is"+methodName, null);
                } catch (SecurityException e1) {
                    e1.printStackTrace();
                } catch (NoSuchMethodException e1) {
                    e1.printStackTrace();
                }
            }
            methodArray[i] = method;
        }
        
        return methodArray;
    }
    
    private static <K, V> Map<K, V> bean2Map(Object javaBean) {
        Map<K, V> ret = new HashMap<K, V>();
        try {
            Method[] methods = javaBean.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().startsWith("get")) {
                    String field = method.getName();
                    field = field.substring(field.indexOf("get") + 3);
                    field = field.toLowerCase().charAt(0) + field.substring(1);
                    Object value = method.invoke(javaBean, (Object[]) null);
                    ret.put((K) field, (V) (null == value ? "" : value));
                }
            }
        } catch (Exception e) {
        }
        return ret;
    }
    
     public static Map objectToMap(Object o){
        return objectToMap(o, "");
      }
    
     private static Map objectToMap(Object o, String prefix)
      {
        Map ret = new HashMap();
        if (o == null)
          return ret;
        try {
          Map objDesc = PropertyUtils.describe(o);

          prefix = (!("".equals(prefix))) ? prefix + "." : "";
          for (Iterator it = objDesc.keySet().iterator(); it.hasNext(); ) {
            String key = it.next().toString();
            Object val = objDesc.get(key);
            if ((val != null) && (val instanceof CrmValueObject) && (!(o.equals(val))))
            {
              ret.putAll(objectToMap(val, prefix + key)); break;
            }
            ret.put(prefix + key, val);
          }
        } catch (Exception e) {
            e.printStackTrace();
          //logger.error(e);
        }
        //logger.debug("Object " + o + " convert to map: " + ret);
        return ret;
      }
     
    public static Map objectToMap(List fieldNameList, Object object)
      {
        Map ret = new HashMap();
        for (Iterator it = fieldNameList.iterator(); it.hasNext(); ) {
          String fieldName = (String)it.next();
          String[] fs = fieldName.split(quote("."));
          try {
            Object o = object;
            for (int i = 0; i < fs.length; ++i) {
              Map objDesc = PropertyUtils.describe(o);
              o = objDesc.get(fs[i]);
              if (o == null)
                break;
            }
            ret.put(fieldName, o);
          } catch (Exception e) {
              e.printStackTrace();
            //logger.error(e);
          }
        }
        return ret;
      }
    
    public static String quote(String s)
      {
        int slashEIndex = s.indexOf("\\E");
        if (slashEIndex == -1)
          return "\\Q" + s + "\\E";

        StringBuffer sb = new StringBuffer(s.length() * 2);
        sb.append("\\Q");
        slashEIndex = 0;
        int current = 0;
        while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
          sb.append(s.substring(current, slashEIndex));
          current = slashEIndex + 2;
          sb.append("\\E\\\\E\\Q");
        }
        sb.append(s.substring(current, s.length()));
        sb.append("\\E");
        return sb.toString();
      }
}
复制代码
分享到:
评论

相关推荐

    Map 转为Object Object 转为 Map java jdk1.4以上

    例如,如果Map有"firstName"和"lastName"两个键,你可以创建一个名为`Person`的类,包含两个属性`firstName`和`lastName`。 ```java public class Person { private String firstName; private String lastName; ...

    对象转换成JSON和Map

    - **对象转Map方法**:Java没有内置的方法直接将对象转换为Map,但我们可以手动实现。这通常涉及遍历对象的属性并创建对应的键值对。也可以使用第三方库如Dozer或ModelMapper来简化这个过程。 - **自定义转换**:...

    将List集合中的map对象转为List&lt;对象&gt;形式实例代码

    本文主要介绍了将List集合中的map对象转为List&lt;对象&gt;形式实例代码的实现方法。该方法可以将List集合中的map对象转换为List&lt;对象&gt;形式,以便于更好地管理和使用数据。 首先,需要了解Java中的List和Map接口。List是...

    java bean和map之间的互转

    这段代码通过遍历Java Bean类的所有getter方法,获取属性名和对应的值,并存入Map中。 反过来,从Map转换为Java Bean的过程可以使用Java的构造器或者无参构造器结合setter方法完成。以下是一个基本的实现: ```...

    Java lambda list转换map时,把多个参数拼接作为key操作

    下面将详细介绍该操作的实现方法和需要注意的两个大坑。 一、Java lambda list转换map时,把多个参数拼接作为key操作 Java lambda list转换map时,把多个参数拼接作为key操作可以使用Collectors.toMap()方法实现。该...

    Java解析和生成XML.pdf

    在实际应用中,开发者应当根据实际需求选择合适的注解,并正确地设置属性值,以保证Java对象与XML文档之间的正确映射。同时,如果遇到特定的数据类型转换问题,需要编写自定义的适配器类来扩展JAXB框架的功能。通过...

    BeanUtils开发包

    通过调用`BeanUtils.copyProperties()`方法,可以将一个JavaBean对象的所有属性值复制到另一个JavaBean对象中,即使两个对象的属性类型不同,BeanUtils也能尝试进行自动转换。例如,从字符串转为整型,或者从日期...

    初级java程序员面试经验分享.pdf,这是一份不错的文件

    `会创建两个对象:一个是在常量池中的`'xyz'`,另一个是在堆上新创建的`String`对象。 4. `shorts1; s1 = s1 + 1;`是有错误的,因为`short`类型的变量与`int`类型相加时,结果会被提升为`int`类型,需要强制类型转换...

    黑马程序员入学Java知识

    - 同一个类中可以有多个同名方法,但参数列表不同。 - 提供多种实现同一功能的方式。 6. **可变参数** - 允许方法接收任意数量的相同类型的参数。 7. **数组简介** - 数组是一种容器,用于存储固定数量的同...

    28个java常用的工具类

    26. **序列化与反序列化工具类**:如`SerializationUtils`,实现了对象的序列化和反序列化,`serialize()`和`deserialize()`分别对应这两个操作。 27. **数据校验工具类**:如`ValidatorUtils`,提供数据验证功能,...

    使用Iterator模式将对象转成String (2).docx

    具体到文档内容,`StringGenerator`和`ObjectIterator`是两个关键类,它们一起工作,将复杂的对象转换为易于理解和调试的字符串表示。 1. **StringGenerator**:这个工具类的主要功能是将任何对象转化为字符串。它...

    BTA 常问的 Java基础39道常见面试题及详细答案.docx

    equals()是Object类中的方法,用于比较两个对象的内容是否相等;而==比较的是两个对象的引用是否指向同一块内存空间。 5. **自动装箱**: 自动装箱是Java编译器自动将基本数据类型转换为其对应的封装类对象的过程...

    JAVA面试题全集

    - `Serializable` 接口用于实现对象序列化。 15. **MVC (Struts的工作流程)** - Struts 的工作流程涉及 ActionServlet、ActionForm、Action 和 View。 16. **路由协议种类及特点** - RIP、OSPF 和 BGP 等是常见...

    面试宝典新版.docx

    对于引用类型,如果两个引用指向同一个对象,==返回true;equals默认行为与==相同,但许多类(如String和Integer)重写了equals方法,用于比较对象内容。 4. Stream常用方法 - map:用于类型转换,将一个集合中的...

    jackson 实体转json 为NULL或者为空不参加序列化(实例讲解)

    然而,在进行这种转换的过程中,常常会遇到一些问题,例如当Java对象的某个属性值为null时,我们可能不希望这个属性在JSON中出现。针对这个问题,本文将介绍两种方法,可以使得在使用Jackson进行序列化时,实体对象...

    2021-2022计算机二级等级考试试题及答案No.4008.docx

    25. Java的Map集合中的元素是以键值对的形式存在的,键是唯一的,用于定位对应的值。 以上是对题目中涉及的计算机知识的详细解释,涵盖了编程语言、网页开发、数据库管理和操作系统等多个领域。

    JDK1.8对于集合操作的简化处理的应用

    - `toMap`: 创建一个Map,键值对可以通过两个函数获得,如`stream.collect(Collectors.toMap(Person::getName, Function.identity()))`将按姓名创建一个Map,值保持原样。 4. **处理后的Stream取第一个值** `find...

    2021-2022计算机二级等级考试试题及答案No.13802.docx

    22. **C语言逻辑运算**:C语言中的逻辑运算符`&&`表示逻辑与,如果两个表达式都为真,则结果为真。在给定的程序段中,x的值为1(true),因为'a'在ASCII码中大于'A',所以`(a&&b)&&(c&gt;'A')`的条件为真。 23. **输入...

Global site tag (gtag.js) - Google Analytics