如何使不可更改的Java类可序列化?

时间:2018-10-04 12:47:01

标签: java serialization wsdl

我有wsdl生成的User类。我不能改变这堂课。我的任务是将会话保存在Redis中而不是Tomcat中。但是经过身份验证后,我得到一个错误,该错误表明类User必须是可序列化的。如何使此类可序列化?

1 个答案:

答案 0 :(得分:0)

您必须为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.
    }
    ...
}