java对象里存流_在java中流式传输后不保存对象属性更改

更新:

好的,所以我把部分代码变灰了,发现导致问题的原因.

我在这里添加了3行代码,注释“这是导致问题的添加代码”.

但我仍然不明白为什么它会影响结果.

我正在开发一个客户端 – 服务器应用程序,它通过ObjectOutputStream和ObjectInputStream发送数据对象.

我注意到一些奇怪的东西让我觉得我可能不完全理解对象引用.

在客户端,我有一个创建并返回User对象的方法:

private static User createNewUser()

{

User newUser = new User();

newUser.name = "Jim";

newUser.phone = "054-6885644";

..

return newUser;

}

我使用此方法创建一个User对象,更改其中一个属性并将其发送到服务器:

User user = createNewUser();

out.writeObject(user); // this is the added code that causes the problem

out.flush(); // this is the added code that causes the problem

system.out.println("old phone number: " + user.phone); // this prints out 054-6885644

user.phone = "052-9008801";

system.out.println("new phone number: " + user.phone); // this prints out 052-9008801

out.writeObject(user);

out.flush();

在服务器端,我读取了对象:

User user = (User) in.readObject(); // this is the added code that causes the problem

User newProfile = (User) in.readObject();

System.out.println("phone number: " + newProfile.phone); // this prints out 054-6885644 (why??)

因此,正如您所看到的,在流式传输对象之前,该属性已更新.但是在服务器反序列化之后,它会获得原始属性值.

这是为什么?

顺便说一句,我尝试在流式传输之前克隆对象(创建一个完全不同的对象,只是复制字段)并且它起作用 – 这个价值没有恢复.

那为什么会这样呢?为什么在流式传输后没有保存对引用对象属性的更改?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值