java 工具类 克隆_java中定义一个CloneUtil 工具类

其实所有的java对象都可以具备克隆能力,只是因为在基础类Object中被设定成了一个保留方法(protected),要想真正拥有克隆的能力,

就需要实现Cloneable接口,重写clone方法。通过克隆方法得到的对象是一个本地的副本。

1、实现Cloneable接口

具体看代码:

class User implements Cloneable{

int age;

public User(int age){

//用this关键字不至于类成员变量与形参混淆

this.age=age;

}

//这里可加@Override也可不加,加了会自动提示是否正确

@Override

public Object clone{

Object o=null;

try{

o=super.clone();

}catch(CloneNotSupportedException e){

e.printStackTrace();

}

}

public String toString(){

return Integer.toString(this.age);

}

}

2、自己手动写一个CloneUtil 工具类,不是实现Cloneable这种方式,但是能达到效果。

package cn.com.util;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

/**

* 对象clone 工具类

* @author

*

*/

public class CloneUtil {

public static Object clone(Serializable obj) {

Object clone = cloneObject(obj);

if (clone == null) {

clone = cloneObject(obj);

}

return clone;

}

public static Object cloneObject(Serializable obj) {

Object anotherObj = null;

ByteArrayOutputStream baos = new ByteArrayOutputStream();

ObjectOutputStream oos = null;

ObjectInputStream ois = null;

try {

oos = new ObjectOutputStream(baos);

oos.writeObject(obj);

byte[] bytes = baos.toByteArray();

ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

ois = new ObjectInputStream(bais);

anotherObj = ois.readObject();

} catch (IOException ex) {

throw new RuntimeException(ex.getMessage(), ex);

} catch (ClassNotFoundException ex) {

throw new RuntimeException(ex.getMessage(), ex);

} catch (StackOverflowError error) {

System.out.println("stack length " + error.getStackTrace().length);

error.printStackTrace();

return null;

} finally {

if (oos != null)

try {

oos.close();

} catch (IOException localIOException3) {

}

if (ois != null)

try {

ois.close();

} catch (IOException localIOException4) {

}

}

return anotherObj;

}

public static int getObjectSize(Serializable obj) {

ByteArrayOutputStream bs = new ByteArrayOutputStream();

try {

ObjectOutputStream os = new ObjectOutputStream(bs);

os.writeObject(obj);

os.flush();

} catch (Exception e) {

throw new RuntimeException(e.getMessage(), e);

}

return bs.size();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值