java中定义一个CloneUtil 工具类
其實(shí)所有的java對(duì)象都可以具備克隆能力,只是因?yàn)樵诨A(chǔ)類Object中被設(shè)定成了一個(gè)保留方法(protected),要想真正擁有克隆的能力,
就需要實(shí)現(xiàn)Cloneable接口,重寫clone方法。通過克隆方法得到的對(duì)象是一個(gè)本地的副本。
1、實(shí)現(xiàn)Cloneable接口
具體看代碼:
class User implements Cloneable{
int age;
public User(int age){
//用this關(guān)鍵字不至于類成員變量與形參混淆
this.age=age;
}
//這里可加@Override也可不加,加了會(huì)自動(dòng)提示是否正確
@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、自己手動(dòng)寫一個(gè)CloneUtil 工具類,不是實(shí)現(xiàn)Cloneable這種方式,但是能達(dá)到效果。
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;
/**
?* 對(duì)象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();
?? ?}
}
?
總結(jié)
以上是生活随笔為你收集整理的java中定义一个CloneUtil 工具类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CountDownLacth详解
- 下一篇: 读取properties