[英]How to make unchangeable java class Serializable?
我有由wsdl生成的User類。 我不能改變這堂課。 我的任務是將會話保存在Redis中而不是Tomcat中。 但是經過身份驗證后,我得到一個錯誤,該錯誤表明類User必須是可序列化的。 如何使此類可序列化?
您必須為User編寫自己的序列化程序。 假設您的用戶以某種方式存儲在會話類中,並且該會話應該被序列化:
public class TheSession implements Serializable
{
...
private transient User user;
...
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject(); // serializes all properties except the transients
// serialize single fields of the User class
oos.writeObject(user.getName());
oos.writeInt(user.getId());
...
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
String userName = (String)ois.readObject;
int userId = ois.readId();
this.user = new User(userName, userId); // assume that we have such a constructor
... // fill the other fields of user.
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.