问题
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