java bean的拷贝
< 返回列表时间: 2020-06-03来源:OSCHINA
1.bean copy package com.qimh.springbootfiledemo.utils; import org.apache.poi.ss.formula.functions.T; import java.lang.reflect.Field; /** * @author * bean 复制 */ public class BeanCopy { /** * bean 的拷贝 * @param srcBean--原始bean * @param destClazz--目标class对象 * 这个<T> T 表示的是返回值T是泛型 * T是一个占位符,用来告诉编译器,这个东西先给我留着,等我编译的时候,告诉你。 * https://www.cnblogs.com/jpfss/p/9929108.html */ public static <T> T beanCopy(Object srcBean,Class<T> destClazz) throws IllegalAccessException, InstantiationException, NoSuchFieldException { if (null != srcBean && null != destClazz){ //获取目标bean的实例 T destBean = destClazz.newInstance(); //获取目标bean所有字段 Field[] fields = destClazz.getDeclaredFields(); for (int i = 0;i < fields.length;i++){ Field field = fields[i]; Object value = BeanEquals.getClassValue(srcBean,field.getName()); //获取目标类的字段 Field destField = destClazz.getDeclaredField(field.getName()); //可访问私有属性 destField.setAccessible(true); //给目标类属性设置值 destField.set(destBean,value); } return destBean; } return null; } }
2.拷贝工具类 package com.qimh.springbootfiledemo.utils; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * @author ex-qiminhui001 * 判断两个bean是否相等 */ public class BeanEquals { /** * 日志操作类 */ private static Logger logger = LoggerFactory.getLogger(BeanEquals.class); /** * 比较两个BEAN或MAP对象的值是否相等 * 如果是BEAN与MAP对象比较时MAP中的key值应与BEAN的属性值名称相同且字段数目要一致 * @param source * @param target * @return */ public static boolean domainEquals(Object source, Object target) { if (source == null || target == null) { return false; } boolean rv = true; if (source instanceof Map) { rv = mapOfSrc(source, target, rv); } else { rv = classOfSrc(source, target, rv); } logger.info("THE EQUALS RESULT IS " + rv); return rv; } /** * 源目标为MAP类型时 * @param source * @param target * @param rv * @return */ 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 */ private static boolean classOfSrc(Object source, Object target, boolean rv) { Class<?> srcClass = source.getClass(); Field[] fields = srcClass.getDeclaredFields(); 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 { if (nameKey.equals("carts")){ System.out.println("field:" + nameKey); } if (nameKey.equals("friends")){ System.out.println("field:" + nameKey); } //数组类型 if (!StringUtils.isEmpty(getClassValue(source, nameKey)) && getClassValue(source, nameKey) instanceof Object[]){ rv = Arrays.equals((Object[])getClassValue(source, nameKey),(Object[])getClassValue(target, nameKey)); break; } 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 */ 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[]) { Person person1 = new Person(); person1.setName("张三"); person1.setAge(20); JSONObject carts = new JSONObject(); carts.put("bmw","宝马"); carts.put("audi","奥迪"); person1.setCarts(carts); person1.setFriends(new String[]{"tom","jim"}); Person person2 = new Person(); person2.setName("张三"); person2.setAge(20); JSONObject carts2 = new JSONObject(); carts2.put("bmw","宝马"); carts2.put("audi","奥迪"); person2.setCarts(carts2); person2.setFriends(new String[]{"tom","jim2"}); System.out.println(domainEquals(person1,person2)); } }
3.目标bean package com.qimh.springbootfiledemo.bean; public class JimPerson { private Integer age; private String name; public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "JimPerson{" + "age=" + age + ", name='" + name + '\'' + '}'; } }
4.原始bean package com.qimh.springbootfiledemo.bean; public class Person { private Integer age; private String name; public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "age=" + age + ", name='" + name + '\'' + '}'; } }
5.测试类 package com.qimh.springbootfiledemo; import com.qimh.springbootfiledemo.bean.JimPerson; import com.qimh.springbootfiledemo.bean.Person; import com.qimh.springbootfiledemo.utils.BeanCopy; public class BeanCopyMain { public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException, InstantiationException { Person person = new Person(); person.setName("张三"); person.setAge(20); JimPerson jimPerson = BeanCopy.beanCopy(person, JimPerson.class); System.out.println("jimPerson:" + jimPerson); } }
热门排行