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)
你能帮忙吗?谢谢!
最佳答案
您正在尝试序列化非Serialized
(即,它没有实现Serializable
接口(interface))对象
试试这个:
Object clonedObject = Utils.copy(new String("Hello");
String
类是可序列化
关于java - 错误信息是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18205456/