我有以下课程
class UserAccount implements Serializable
{
public String username;
public String password;
public UserAccount()
{
username = "defaultUsername";
password = "defaultPassword";
}
public UserAccount(String u, String p)
{
username = u;
password = p;
}
private void readObject(ObjectInputStream o)
throws IOException, ClassNotFoundException
{
//username = (String)o.readObject();
o.defaultReadObject();
}
private void writeobject(ObjectOutputStream o)
throws IOException, ClassNotFoundException
{
//o.defaultWriteObject();
o.writeObject(username);
}
public String toString()
{
return username + ", " + password;
}
}
我编写了以下代码片段来序列化和反序列化它的一个实例.
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("out.dat")));
out.writeObject(new UserAccount("test", "test2"));
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File("out.dat")));
UserAccount u = (UserAccount)in.readObject();
in.close();
System.out.println(u);
我使用writeObject()钩子自定义序列化,这样,我只是持久化用户名.但是当我回读对象时,我会进行默认的反序列化.
我期待输出是测试,null,而输出是test,test2
基本上我期望成员密码为空,因为我没有坚持它.任何人都可以帮我理解如何将密码初始化为test2.
我还验证了在反序列化过程中没有对构造函数进行调用[我知道它不会被创建,但我仍然检查过].
提前致谢.
解决方法:
将transient关键字用于变量以使它们不被序列化.这可能是斯卡弗曼答案的另一种解决方案.
标签:java,serialization
来源: https://codeday.me/bug/20190726/1541838.html