京东6.18大促主会场领京享红包更优惠

 找回密码
 立即注册

QQ登录

只需一步,快速开始

java对象拷贝

2021-11-4 18:42| 发布者: zhaojun917| 查看: 1573| 评论: 0

摘要: 对于属性名一样的对象,把对象A的属性值拷贝给对象Bpublic static void main(String args) throws ParseException { demo1 d=new demo1(); d.setName("zy"); d.setAge(20); d.setMsg("zy"); demo2 d2 ...
对于属性名一样的对象,把对象A的属性值拷贝给对象B

public static void main(String[] args) throws ParseException {
         demo1 d=new demo1();
         d.setName("zy");
         d.setAge(20);
         d.setMsg("zy");
         demo2 d2=new demo2();
 
         System.out.println("拷贝前:");
         System.out.println(d.toString());
         System.out.println(d2.toString());
         change(d,d2);
         System.out.println("拷贝后:");
         System.out.println(d.toString());
         System.out.println(d2.toString());
}
 
     /**
      * 对象1的属性值拷贝给对象2
      * @param o1
      * @param o2
      */
public static void change(Object o1,Object o2){
         try {
             Class<?> o1Class = o1.getClass();
             Class<?> o2Class = o2.getClass();
             Field[] o1f = o1Class.getDeclaredFields();
             Field[] o2f = o2Class.getDeclaredFields();
 
             for (int i = 0; i < o1f.length; i++) {
                 String o1name = o1f[i].getName();
                 for (int j = 0; j < o2f.length; j++) {
                     String o2name = o2f[j].getName();
                     if(o1name.equals(o2name)){
                         o2f[j].setAccessible(true);
                         o2f[j].set(o2,o1f[i].get(o1));
                     }
                 }
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
 
}
 
@Data
class demo1{
    String name;
    Integer age;
    String msg;
}
@Data
class demo2{
    String name;
    Integer age;
    String msg2;
}


只有name和age字段名字一样,才拷贝。最基础的demo,还未做类型判断
关闭

站长推荐上一条 /6 下一条

QQ|手机版|小黑屋|梦想之都-俊月星空 ( 粤ICP备18056059号 )|网站地图

GMT+8, 2025-7-1 19:41 , Processed in 0.040579 second(s), 18 queries .

Powered by Mxzdjyxk! X3.5

© 2001-2025 Discuz! Team.

返回顶部