package example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.Object;
class Utils {
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
}
public class mytest {
public static void main(String[] args) throws IOException {
Object clonedObject = Utils.copy(new Object());
clonedObject.notifyAll();
}
}
上面的代码是通过将对象更改为字节数组来展示深拷贝的工作原理。但是 myeclipse 给出了以下错误消息,我不知道为什么。
java.io.NotSerializableException: java.lang.Object
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326)
at example.Utils.copy(mytest.java:17)
at example.mytest.main(mytest.java:37)
Exception in thread "main" java.lang.NullPointerException
at example.mytest.main(mytest.java:38)
能否请你帮忙?谢谢!