import java.io.*;
@SuppressWarnings("all")
public class CloneBySerializable implements Serializable {
private int j;
private Thing thing;
public CloneBySerializable(int j) {
this.j = j;
this.thing = new Thing(j);
}
public static void main(String[] args) {
CloneBySerializable[] arr = new CloneBySerializable[10000];
for (int i = 0, length = arr.length; i < length; i++) {
arr[i] = new CloneBySerializable(i);
}
try {
long t1 = System.currentTimeMillis();
ByteArrayOutputStream buf =
new ByteArrayOutputStream();
ObjectOutputStream o =
new ObjectOutputStream(buf);
for(int i = 0; i < arr.length; i++)
o.writeObject(arr[i]);
ObjectInputStream in =
new ObjectInputStream(
new ByteArrayInputStream(
buf.toByteArray()));
CloneBySerializable[] copy = new CloneBySerializable[arr.length];
for(int i = 0; i < copy.length; i++)
copy[i] = (CloneBySerializable) in.readObject();
long t2 = System.currentTimeMillis();
System.out.println("Duplication via serialization: " +
(t2 - t1) + " Milliseconds");
} catch (Exception ex) {
ex.printStackTrace();
}
//单例类防止复制
Dog newDog = (Dog) deepCopy(Dog.INSTANCE);
System.out.println(newDog == Dog.INSTANCE); //true
}
static class Dog extends Exception {
public static final Dog INSTANCE = new Dog();
private Dog() {}
public String toString(){
return "Woof";
}
//用于解决返回新实例的问题
private Object readResolve(){
return INSTANCE;
}
}
static public Object deepCopy(Object obj){
try{
ByteArrayOutputStream bos =
new ByteArrayOutputStream();
new ObjectOutputStream(bos).writeObject(obj);
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray());
return new ObjectInputStream(bin).readObject();
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
}
@SuppressWarnings("all")
class Thing implements Serializable {
private int i;
public Thing(int i) {
this.i = i;
}
}
java序列化实现的对象复制性能比clone差
一个实现了Serializable 的单例类,必须有一个readResolve 方法,用以返回它的唯一的实例。
对一个实现了Serializable 的类进行了扩展,或者实现了一个扩展自Serializable 的接口,
使得我们在无意中实现了Serializable。