首先呢,我们先新建一个类Apple(最近爱吃水果...)代码如下:
class Apple implements Serializable {
private int[] prices;
private int size;
public int[] getPrices() {
return prices;
}
public void setPrices(int[] prices) {
this.prices = prices;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
@Override
public String toString() {
return "Apple{" +
"prices=" + Arrays.toString(prices) +
", size=" + size +
'}';
}
}
首先Apple实现了Serializable接口,因为实现java.io.Serializable 接口的类是可序列化的。其实是在告诉JVM此类可被序列化,可被默认的序列化机制序列化(变成二进制流)。 然后我们新建一个克隆执行类,用来通过Object流实现拷贝(写入和读出),代码如下:
class StreamClone{
public static <T> T clone(T cloneBe) throws IOException {
ByteArrayOutputStream botp = null;
ObjectOutputStream ootp = null;
ByteArrayInputStream bipt = null;
ObjectInputStream oipt = null;
T cloneResult = null;
try {
botp = new ByteArrayOutputStream();
ootp = new ObjectOutputStream(botp);
//将被拷贝的对象写入流里
ootp.writeObject(cloneBe);
bipt = new ByteArrayInputStream(botp.toByteArray());
oipt = new ObjectInputStream(bipt);
//从流中读出对象
cloneResult = (T) oipt.readObject();
} catch (Exception e) {
e.printStackTrace();
}finally {
ootp.close();
botp.close();
bipt.close();
oipt.close();
}
return cloneResult;
}
}
通过泛型和Object流实现对任意对象进行克隆,我们测试一下:
public static void main(String[] args) throws CloneNotSupportedException, IOException {
int [] prices = new int[2];
prices[0] = 10;
prices[1] = 20;
Apple apple1 = new Apple();
apple1.setSize(15);
apple1.setPrices(prices);
Apple apple2 = StreamClone.clone(apple1);
System.out.println("克隆之后 apple1" + apple1 + "/t" + "apple2" + apple2 );
int[] prices1 = apple2.getPrices();
prices1[0] = 9;
System.out.println("修改之后 apple1" + apple1 + "/t" + "apple2" + apple2);
}
结果如下:
克隆之后 apple1Apple{prices=[10, 20], size=15}/tapple2Apple{prices=[10, 20], size=15}
修改之后 apple1Apple{prices=[10, 20], size=15}/tapple2Apple{prices=[9, 20], size=15}
可以看到apple2修改之后对apple1并没有造成任何修改,apple2的prices发生了改变,实现了深拷贝,虽然代码比较多,但是使用起来非常方便也是比较高效的。