Double Brace initialization and serialization

无人久伴 提交于 2019-12-13 16:00:55

问题


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 :

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 ?


回答1:


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.

One solution would be to let the setter return this, instead of being void. Then you can chain setters.

UserVO vo = new UserVO().setIndex("admin");


来源:https://stackoverflow.com/questions/29363254/double-brace-initialization-and-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!