zoukankan      html  css  js  c++  java
  • Java将一个对象的属性值copy给另一个相同的对象

    import java.beans.BeanInfo;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    
    
    public class CopyUtils {
        public static void Copy(Object source, Object dest) throws Exception {
            // 获取属性
            BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(),Object.class);
            PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();
    
            BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(),Object.class);
            PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();
    
            try {
                for (int i = 0; i < sourceProperty.length; i++) {
    
                    for (int j = 0; j < destProperty.length; j++) {
    
                        if (sourceProperty[i].getName().equals(destProperty[j].getName())  && sourceProperty[i].getPropertyType() == destProperty[j].getPropertyType()) {
                            // 调用source的getter方法和dest的setter方法
                            destProperty[j].getWriteMethod().invoke(dest,sourceProperty[i].getReadMethod().invoke(source));
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                throw new Exception("属性复制失败:" + e.getMessage());
            }
        }
        public static void main(String[] args) throws Exception{
            Device device = new Device();
            device.setDevId("99999");
            Device devices = new Device();
            CopyUtils.Copy(device,devices);
            System.out.println(devices.getDevId());
        }
    }
  • 相关阅读:
    java web 资源文件读取
    页面跳转
    验证码的随机图片
    spring 注解
    回文字符串系列问题
    【leetcode】Find All Anagrams in a String
    斐波那契数列
    【leetcode】 First Missing Positive
    Trapping Rain Water
    区间合并问题
  • 原文地址:https://www.cnblogs.com/shoose/p/12930737.html
Copyright © 2011-2022 走看看