也许你的MemcachedClient
类中的一个对象不能被序列化。您有 2 个选项来解决问题:
确保那里的所有类都实现了Serializable
接口。
public class MemcachedClient {
//AnotherClass must implement Serializable too.
private AnotherClass anotherClassInstance;
}
如果另一个类没有实现Serializable
(并且你不能修改这些类来创建它们Serializable
),那么添加transient
关键字,这样这些对象就不会被序列化
public class MemcachedClient {
//AnotherClass doesn't implement Serializable.
private transient AnotherClass anotherClassInstance;
}
如果您AnotherClass
在反序列化MemcachedClient
对象时必须有一个实例,那么您可以编写根据readObject(ObjectInputStream is)
需要创建一个实例:
public class MemcachedClient {
//AnotherClass doesn't implement Serializable.
private transient AnotherClass anotherClassInstance;
private void writeObject(ObjectOutputStream os) throws IOException, ClassNotFoundException {
os.defaultWriteObject();
}
private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException {
is.defaultReadObject();
anotherClassInstance = new AnotherClass();
//more logic to get a consistant AnotherClass instance.
}
}
根据 Brian 的评论,假设此类MemcachedClient
来自第三方库并且您无法修改它,您将遇到第 2 点中描述的场景:
public class MyClass {
//MemcachedClient can't be modified and doesn't implement Serializable interface
//the only solution would be using the transient modifier
private transient MemcachedClient memcachedClient;
//MyClass attributes and methods...
//If you need to keep a MemcachedClient instance when deserializing the object
//just write the readObject method
private void writeObject(ObjectOutputStream os) throws IOException, ClassNotFoundException {
os.defaultWriteObject();
}
private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException {
is.defaultReadObject();
memcachedClient= new MemcachedClient();
//more logic to get a consistant MemcachedClient instance.
}
}