Question

I tried to serialize an ArrayList with JAXB and failed. Is this because elementData is marked as transient?

Why does the ArrayList implement the Serializable Inferface and has it's data transient?

I try to serialize an ArrayList of Serializables:

JAXBElement<ArrayList> jaxbElement = new JAXBElement<ArrayList>(new QName(ArrayList.class.getSimpleName()), ArrayList.class, allEntities);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(jaxbElement, System.out);

How to do this via JAXB?

Était-ce utile?

La solution

ArrayList implements Serializable, so it can be serialized, that's exactly why the private backing array is transient, so it is not serialized along with other data in the class, since all is handled by ArrayList's writeObject and readObject methods.

It does this because it provides custom readObject and writeObject methods that do a better job of serialization than the default. Specifically, the writeObject method writes just the size and the sequence of elements. This avoids serializing the private array object which 1) has its own header and overheads, and 2) is typically padded with nulls. The space saving can be significant.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top