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;

最新文章

  1. 解决 PHPExcel 长数字串显示为科学计数
  2. hive修改 表/分区语句
  3. 用C#打开文件对话框的方法和简单使用的程序
  4. char,string和CString转换
  5. Html A标签中 href 和 onclick 同时使用的问题 优先级别
  6. 将博CMS安全分析报告-橘皮书
  7. selenium 一个简单的流程
  8. http://www.yihaomen.com/article/java/302.htm
  9. xml配置与使用
  10. (原+转)ubuntu终端输出彩色文字
  11. 让2个并列的div根据内容自动保持同等高度js
  12. ubuntu下vsftpd配置
  13. 为多态基类声明virtual析构函数
  14. Eureka客户端注册多网卡下IP选择问题
  15. 平板电脑安装Ubuntu教程
  16. Calling Matlab function from python: “initializer must be a rectangular nested sequence”
  17. How to export a model from SolidWorks to Google SketchUp
  18. grafana-simple-json-datasource 用于连接各种grafana不支持的数据源
  19. codevs 2185 最长公共上升子序列
  20. Anaconda 包管理工具 conda 进行虚拟环境管理入门

热门文章

  1. Jupyter Notebook 快捷键
  2. 深入理解JS函数节流和去抖动
  3. vue-resource文档详细解读
  4. Hibernate连接MySQL
  5. VC在windows中打开文件夹并选中文件
  6. Android Studio 项目中集成百度地图SDK报Native method not found: com.baidu.platform.comjni.map.commonmemcache.JNICommonMemCache.Create:()I错误
  7. PHP基础知识(一)
  8. Android资源图片读取机制
  9. ASP.NET请求管道、应用程序生命周期、整体运行机制
  10. asp.net 查询本地excel 获取信息