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;

 

posted @ 2017-07-02 10:18  牵牛花  阅读(873)  评论(0编辑  收藏  举报