zoukankan      html  css  js  c++  java
  • java对象实现深复制的方法


    p2 = (Person)org.apache.commons.lang3.ObjectUtils.cloneBean(p); Person p2 = new Person(); p2 = (Person)org.apache.commons.lang3.ObjectUtils.cloneBean(p); System.out.println(p2); p2.name = "wewr"; System.out.println(p2); System.out.println(p); Person{age=1, name='adfa', p=null} Person{age=1, name='wewr', p=null} Person{age=1, name='adfa', p=null}

     对象复制的一个使用场景,在使用redis和Hbase处理两个库的事务时,要手动实现事务,在修改一些数据时要先复制一份,在hbase或者dedis做updata操作失败时还原用.

    在hbase中没有事务,需要自己实现事务,此时也用到了对象的深复制

    第二种方法,通过序列化和反序列话实现,此时被序列化的类需要 implements Serializable

    package asdfasdf;
    
    import org.apache.commons.beanutils.BeanUtils;
    import org.apache.commons.lang3.ObjectUtils;
    import org.apache.hadoop.mapreduce.lib.input.LineRecordReader;
    import org.junit.Test;
    
    import java.io.*;
    import java.lang.reflect.InvocationTargetException;
    
    /**
     * Hello world!
     *
     */
    public class App 
    {
    
    
        @Test
       public void test1() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
    
            Person p = new Person();
            p.age = 1;
            p.name = "adfa";
    
         Person p2 =  new Person();
          p2 =  (Person)org.apache.commons.beanutils.BeanUtils.cloneBean(p);
         System.out.println(p2);
         p2.name = "wewr";
         System.out.print(p2);
         System.out.print(p);
    
    
       }
    
       @Test
       public void test2() throws IOException, ClassNotFoundException {
           Person p = new Person();
           p.age = 1;
           p.name = "adfa";
           Person p2 =  null;
           ByteArrayOutputStream baos = new ByteArrayOutputStream();
           ObjectOutputStream oos = new ObjectOutputStream(baos);
           oos.writeObject(p);
           // 将流序列化成对象
           ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
           ObjectInputStream ois = new ObjectInputStream(bais);
           p2 = (Person) ois.readObject();
           System.out.println(p2);
           p2.name = "wewr";
           System.out.println(p2);
           System.out.println(p);
       }
    }
    public class Person implements Serializable{
        private static final long serialVersionUID = 369285298572941L;  //最好是显式声明ID
    
        int age;
        String name;
        Person p;
  • 相关阅读:
    <2016-1-28>
    <页面里折合与打开>
    右上角鼠标滑过展开收缩动画效果js代码的演示页面
    30款css3实现的鼠标经过图片显示描述特效
    dede让channelartlist标签支持currentstyle属性 完美解决
    织梦导航 currentstyle 点击li添加class类 样式
    论坛首页显示板块,但没有权限点不进去
    医疗窗口右下角弹出抖动效果
    joomla搬家之后打不开 首页404错误
    Discuz X3游客看小图功能导致文字内容隐藏的【修复方法】
  • 原文地址:https://www.cnblogs.com/rocky-AGE-24/p/7105271.html
Copyright © 2011-2022 走看看