Re: Getting raw data of an object in memory
On 2010-06-23 22:20:05 -0400, Boris Punk said:
Is there anyway to do this? Serialization looks cumbersome and I want
to dump the data of an object onto disk.
how do you get a representation of this in byte form? It can't be that
difficult to grab from memory, dump to disk, then retrieve back into
This is one of the major differences between Java and its most obvious
ancestors: Java does not specify nor expose anything about the internal
representations of objects to programs. This has two advantages: the
JVM is free to reorganize objects much more freely than you might
expect, and it's not possible for a programmer to introduce "invalid"
objects, accidentally or otherwise.
You can *define* a byte-oriented or text-oriented representation for
your objects, and that's exactly what the built-in serialization
protocol does: what comes out is not the JVM's in-memory
representation; instead, ObjectOutputStream builds up a description
according to published and documented protocol rules. The resulting
byte stream is fairly resilient to changes in the runtime environment:
a serialized blob from Java 1.0 is theoretically still deserializable
into an object under Java 1.6 (the current version), more than ten
years later, assuming you have a compatible class definition around to
deserialize it with.
You're not limited to using the built-in (and rather opaque)
byte-oriented format, either: there are a lot of easy-to-use object
marshalling libraries for a lot of different formats out there. XStream
and JAXB can marshal and unmarshal objects to and from XML with very
little code investment, and libraries like gson can do the same with
JSON, giving you some good options for human-readable and
human-debuggable representations. Libraries like Google's protocol
buffers give you some more flexibility in designing your own
byte-oriented representations of your objects, if you prefer.
Hope that helps give you some idea as to where to start looking,