[英]Double Brace initialization and serialization
I've noticed a strange behavior, when using double brace initialization, the initialized object serialization fails : 我注意到一个奇怪的行为,当使用双括号初始化时,初始化的对象序列化失败:
queueVO.setUser(new UserVO() {{setIndex("admin");}});
result in the following error when sending the object to a JMS queue : 将对象发送到JMS队列时导致以下错误:
javax.jms.JMSException: Failed to serialize object
at org.hornetq.jms.client.HornetQObjectMessage.setObject(HornetQObjectMessage.java:139)
whereas everything is running fine otherwise 否则一切运行正常
queueVO.setUser(new UserVO());
queueVO.getUser().setIndex("admin");
I know that this syntactic sugar lead to the creation of an anonymous class but i don't understand why it breaks the serializable contract. 我知道这种语法糖会导致创建一个匿名类,但是我不明白为什么它破坏了可序列化的契约。
Can someone explain me what's happening here ? 有人可以解释一下这里发生了什么吗?
The created anonymous class is not static , so has a <SurroundingClass>.this
, which would be serialized too, or worse become null after the object will be reloaded. 创建的匿名类不是静态的 ,因此还有一个
<SurroundingClass>.this
,该类也将被序列化,或者更糟糕的是,将在重新加载对象后变为null。
One solution would be to let the setter return this, instead of being void. 一种解决方案是让setter返回此值,而不是使其无效。 Then you can chain setters.
然后,您可以设置链结。
UserVO vo = new UserVO().setIndex("admin");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.