这个是非原创的,利用了Java的序列化使得简单的代码就完成了任务,但要注意这个方法性能不是最优的,比调用对象的clone()方法要慢4到10倍吧。
class SerialClone {
public static T clone(T x) {
try {
return cloneX(x);
} catch (IOException e) {
throw new IllegalArgumentException(e);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
}
}
private static T cloneX(T x) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
CloneOutput cout = new CloneOutput(bout);
cout.writeObject(x);
byte[] bytes = bout.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
CloneInput cin = new CloneInput(bin, cout);
@SuppressWarnings("unchecked")
T clone = (T) cin.readObject();
return clone;
}
private static class CloneOutput extends ObjectOutputStream {
Queue<Class> classQueue = new LinkedList<Class>();
CloneOutput(OutputStream out) throws IOException {
super(out);
}
@Override
protected void annotateClass(Class c) {
classQueue.add(c);
}
@Override
protected void annotateProxyClass(Class c) {
classQueue.add(c);
}
}
private static class CloneInput extends ObjectInputStream {
private final CloneOutput output;
CloneInput(InputStream in, CloneOutput output) throws IOException {
super(in);
this.output = output;
}
@Override
protected Class resolveClass(ObjectStreamClass osc)
throws IOException, ClassNotFoundException {
Class c = output.classQueue.poll();
String expected = osc.getName();
String found = (c == null) ? null : c.getName();
if (!expected.equals(found)) {
throw new InvalidClassException("Classes desynchronized: " +
"found " + found + " when expecting " + expected);
}
return c;
}
@Override
protected Class resolveProxyClass(String[] interfaceNames)
throws IOException, ClassNotFoundException {
return output.classQueue.poll();
}
}
}
My name is Hugo Zhu.



