use*_*138 3 java serialization
我有以下课程
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我编写了以下代码片段来序列化和反序列化它的一个实例.
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);
Run Code Online (Sandbox Code Playgroud)
我正在使用writeObject()钩子定制序列化,这样,我只是坚持了username.但是当我回读对象时,我会进行默认的反序列化.
我期待输出是在输出test, null时test, test2
基本上我期待这个成员password,null因为我没有坚持下去.谁能帮我理解密码的初始化方式test2.
我还验证了在反序列化过程中没有对构造函数进行调用[我知道它不会被创建,但我仍然检查过].
提前致谢.
| 归档时间: |
|
| 查看次数: |
828 次 |
| 最近记录: |